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