The @JsonAdapte คำอธิบายประกอบ r สามารถใช้ที่ระดับฟิลด์หรือคลาสเพื่อระบุ Gson TypeAdapter สามารถใช้คลาสเพื่อแปลงวัตถุ Java เป็นและจาก 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"}}