@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<Integer> {
@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"}}