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"}}