English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
@JsonAdapte 现场 또는 클래스 수준에서 사용할 수 있는 주석은 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())); } } //고객 분류 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"}}