How to implement custom JsonAdapter using Gson in Java?

JavaJSONObject Oriented ProgrammingProgramming

The @JsonAdapter annotation can be used at field or class level to specify the Gson. The TypeAdapter class can be used to convert Java objects to and from JSON. By default, Gson library converts application classes to JSON by 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 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();
   }
}

Output

{"customerId":{"customerId":"101"}}
raja
Published on 20-Nov-2019 16:19:15
Advertisements