- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement custom JsonAdapter using Gson in Java?
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"}}
Advertisements