The @JsonAdapte r টীকা Gson নির্দিষ্ট করতে ক্ষেত্র বা শ্রেণী স্তরে ব্যবহার করা যেতে পারে। TypeAdapter ক্লাস 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
class Customer {
@JsonAdapter(CustomJsonAdapter.class)
Integer customerId = 101;
}
// CustomJsonAdapter class
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"}}