English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

如何在Java中使用Gson实现自定义JsonAdapter?

 @JsonAdapte I commenti // possono essere utilizzati a livello di campo o di classe per specificare GSON. IlTypeAdapterLa classe può essere utilizzata per convertire oggetti Java in JSON. Di default, la libreria Gson converte le classi dell'applicazione in JSON utilizzando gli adattatori di tipo integrati, ma possiamo sovrascrivere questo comportamento fornendo un adattatore di tipo personalizzato.

Sintassi

@Retention(value=RUNTIME)
@Target(value={TYPE,FIELD})
public @interface JsonAdapter

Esempio

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()));
   }
}
//Classificazione dei clienti
class Customer {
   @JsonAdapter(CustomJsonAdapter.class)
   Integer customerId = 101;
}
//Classe 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();
   }
}

Risultato di output

{"customerId":{"customerId":"101"}}