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

How to implement custom JsonAdapter using Gson in Java?

 @JsonAdapte Comments can be used at the field or class level to specify GSON. TheTypeAdapterThe class can be used to convert Java objects to JSON. By default, the Gson library converts application classes to JSON using built-in type adapters, but we can override it by providing custom type adapters.

Syntax

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

Example

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 Classification
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();
   }
}

Output Result

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