@JsonAdapte r 주석은 필드 또는 클래스 수준에서 Gson을 지정하는 데 사용할 수 있습니다. TypeAdapter 클래스를 사용하여 Java 객체를 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
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"}}