
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Custom JSON Serialization with Gson in Java
Custom JSON serialization
Custom JSON Serialization means defining how your Java objects should be converted to JSON format. This is useful when you want to control the JSON output, such as changing field names, excluding certain fields, or formatting the data in a specific way.
In this tutorial, we will create a custom serializer for a Java object using the Gson library. We will define a class Person with fields for name and age, and then create a custom serializer to control how this object is converted to JSON.
To use Gson library, we need to add the Gson library to our project. If you are using Maven, add this to your pom.xml file:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
If you are not using Maven, you can download the jar file from here. The following are the steps to implement custom JSON serialization with Gson:
- First, import the Gson library, as discussed above.
- Then create a class Person with fields for name and age.
- Then create a custom serializer class that implements the JsonSerializer interface.
- In the custom serializer, override the serialize method to define how the object should be converted to JSON.
- Then create an instance of GsonBuilder and register the custom serializer using the registerTypeAdapter method.
- Finally, create a Gson instance and use it to serialize the object.
Example
Following is an example of custom JSON serialization with Gson:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; public class CustomJsonSerializationExample { public static void main(String[] args) { // Create a Person object Person person = new Person("Ansh", 23); // Create a custom serializer for the Person class GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Person.class, (JsonSerializer<Person>) (src, typeOfSrc, context) -> { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("fullName", src.getName()); jsonObject.addProperty("yearsOld", src.getAge()); return jsonObject; }); // Create a Gson instance with the custom serializer Gson gson = gsonBuilder.create(); // Serialize the Person object to JSON String json = gson.toJson(person); System.out.println(json); } }
Following is the output of the above code:
{"fullName":"Ansh","yearsOld":23}