Annotation @JsonAdapter สามารถใช้ระดับ field หรือ class เพื่อระบุ Gson คลาส TypeAdapter ใช้แปลง Java objects ไปและมาจาก JSON โดยค่าเริ่มต้น Gson library แปลง application classes เป็น JSON โดยใช้ built-in type adapters แต่เราสามารถ override ได้โดยให้ custom type adapters
Syntax
@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();
}
}
Output
{"customerId":{"customerId":"101"}}