如何在 Java 中使用 Gson 實現自定義 JsonAdapter?


 @JsonAdapter 註釋可以用於欄位或類級別,以指定 Gson。TypeAdapter 類可用於將 Java 物件轉換為 JSON,再從 JSON 轉換為 Java 物件。預設情況下,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"}}

更新時間: 09 年 7 月 2020

2K+ 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.