@JsonAdapter एनोटेशन का उपयोग फील्ड या क्लास स्तर पर Gson को निर्दिष्ट करने के लिए किया जा सकता है। TypeAdapter क्लास का उपयोग जावा ऑब्जेक्ट्स को JSON से और JSON में बदलने के लिए किया जा सकता है। डिफ़ॉल्ट रूप से, Gson लाइब्रेरी बिल्ट-इन टाइप एडाप्टर का उपयोग करके एप्लिकेशन क्लासेस को JSON में बदलती है लेकिन हम कस्टम टाइप एडाप्टर प्रदान करके इसे ओवरराइड कर सकते हैं।
सिंटैक्स
@Retention(value=RUNTIME)
@Target(value={TYPE,FIELD})
public @interface JsonAdapter
उदाहरण
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class JsonAdapterTest {
public static void main(String[] args) {
Gson gson = new Gson();
System.out.println(gson.toJson(new Customer()));
}
}
// Customer क्लास
class Customer {
@JsonAdapter(CustomJsonAdapter.class)
Integer customerId = 101;
}
// CustomJsonAdapter क्लास
class CustomJsonAdapter extends TypeAdapter {
@Override
public Integer read(JsonReader jreader) throws IOException {
return null;
}
@Override
public void write(JsonWriter jwriter, Integer customerId) throws IOException {
jwriter.beginObject();
jwriter.name("customerId");
jwriter.value(String.valueOf(customerId));
jwriter.endObject();
}
}
आउटपुट
{"customerId":{"customerId":"101"}}