Serialization of Java objects using Google’s Gson library
This post will discuss the serialization and deserialization of Java objects using Google’s Gson library.
Nowadays, almost all RESTful web services consume and produce JSON data instead of XML. Unfortunately, Java SE doesn’t support converting JSON to Java Object (and vice-versa). But there are many third-party libraries available that are very reliable and offer high performance. One such library is Gson.
Gson is a Java library that can be used to convert Java objects into their JSON representation. We can also use it to convert a JSON string to an equivalent Java object. Gson provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa.
- Gson does not require additional modifications to classes of serialized/deserialized objects as it uses reflection.
- Gson cannot serialize any transient fields as a transient keyword in Java indicates that a field should not be serialized.
- Gson will not work on objects with recursive references.
- Gson requires the class to have a default no-args constructor. If the no-args constructor is not provided, we can register an
InstanceCreatorwith Gson, allowing us to deserialize instances of classes.
In fact, Gson can deserialize a class even without a no-args constructor or registered InstanceCreator. Try removing the no-args constructor from the following code, and the code will run fine. This StackOverflow post explains it!
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import com.google.gson.Gson; import java.util.Arrays; import java.util.HashSet; import java.util.Set; class Student { private String id; private Set<String> subjects; public Student(String id) { this.id = id; subjects = new HashSet<>(Arrays.asList("Maths", "Science")); } private Student() {} @Override public String toString() { return Arrays.asList(id, subjects.toString()).toString(); } } class Person { private String name; private int age; private Student student; public Person(String name, int age) { this.name = name; this.age = age; student = new Student(name.replaceAll("\\s+", "_") + "_" + String.valueOf(age)); } private Person() {} @Override public String toString() { return Arrays.asList(name, String.valueOf(age), student.toString()) .toString(); } } // Demonstrate serialization/deserialization of Java objects using // Google's GSON library class Main { public static void main(String[] args) { Person person = new Person("Jon Snow", 22); Gson gson = new Gson(); // Serialize object – Convert `Person` object to JSON string String jsonString = gson.toJson(person); System.out.println("Converting Person object to JSON string:\n" + jsonString); // Unserialize object – Convert JSON string back to `Person` object Person p = gson.fromJson(jsonString, Person.class); System.out.println("\nConverting JSON string to Person object:\n" + p.toString()); } } |
Output:
Converting Person object to JSON string:
{"name":"Jon Snow","age":22,"student":{"id":"Jon_Snow_22","subjects":["Maths","Science"]}}
Converting JSON string to Person object:
[Jon Snow, 22, [Jon_Snow_22, [Maths, Science]]]
Gson is highly customizable. We can use GsonBuilder to construct a Gson instance when we need to set configuration options other than the default. There are many interesting methods provided by GsonBuilder to set the custom configuration for the Gson instance. The complete list can be seen here. The following example shows how to use the GsonBuilder to construct a Gson instance using the following methods:
serializeNulls(): By default, Gson excludes all null fields during serialization. This method configures Gson to serialize null fields as well.setPrettyPrinting(): This method configures Gson to output JSON for pretty-printing.setFieldNamingStrategy(FieldNamingStrategy): This method configures Gson to apply a specific naming policy strategy to an object’s field during serialization and deserialization.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Arrays; import java.util.HashSet; import java.util.Set; class Student { private String id; private Set<String> subjects; public Student(String id) { this.id = id; subjects = new HashSet<>(Arrays.asList("Maths", "Science")); } private Student() {} @Override public String toString() { return Arrays.asList(id, subjects.toString()).toString(); } } class Person { private String name; private int age; private Student student; public Person(String name, int age) { this.name = name; this.age = age; // set `null` in order for `serializeNulls()` to work student = new Student(null); } private Person() {} @Override public String toString() { return Arrays.asList(name, String.valueOf(age), student.toString()) .toString(); } } // Demonstrate serialization/deserialization of Java objects using // Google's GSON library class Main { public static void main(String[] args) { Person person = new Person("Jon Snow", 22); Gson gson = new GsonBuilder() .setPrettyPrinting() .serializeNulls() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .create(); // Creates a Gson instance // Serialize object – Convert `Person` object to JSON string String jsonString = gson.toJson(person); System.out.println("Converting Person object to JSON string:\n" + jsonString); // Unserialize object – Convert JSON string back to `Person` object Person p = gson.fromJson(jsonString, Person.class); System.out.println("\nConverting JSON string to Person object:\n" + p.toString()); } } |
Output:
Converting Person object to JSON string:
{
"Name": "Jon Snow",
"Age": 22,
"Student": {
"Id": null,
"Subjects": [
"Maths",
"Science"
]
}
}
Converting JSON string back to Person object:
[Jon Snow, 22, [null, [Maths, Science]]]
That’s all about serialization of Java objects using Google’s Gson library.
Also See:
Useful JSON Tools:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)