All modern applications generally fetch data from remote services (e.g. REST or SOAP) that is mostly either XML or JSON format. Gson helps applications in Java-JSON serialization and deserialization automatically (as well as manually, if needed, using simple toJson()
and fromJson()
methods).
Gson can work with arbitrary Java objects including pre-existing objects that we do not have sourcecode of. The best benefit of Gson is that it does not make it mandatory to add annotations into Java classes until we are doing something very specific for certain member fields.
Note that the Gson
instance does not maintain any state while invoking JSON operations. It makes the Gson instance to be thread-safe. So, we are free to reuse the same object for multiple JSON serialization and deserialization operations.
1. Setting Up Gson
Refer to the latest version of Gson from its Maven repo page.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
The Gradle dependency is as follows:
dependencies {
implementation 'com.google.code.gson:gson:2.8.9'
}
2. Creating Gson Instance
The most straightforward way to have a Gson instance is to call its default empty constructor. It creates the Gson instance with the following default configurations:
- Generates compact JSON representations by removing all the unneeded white-spaces.
- Omits all the fields that are null. The nulls in arrays are kept as is.
- Uses the default Date format is the same as
DateFormat.DEFAULT
that ignores the millisecond portion. - Excludes
transient
orstatic
fields from consideration for serialization and deserialization. - Ignores @Expose and @Since annotations.
Gson gson = new Gson();
To override the default configuration, we can use the GsonBuilder class. After calling its constructor, we can call its various configuration methods, and finally call create() to get the Gson instance.
Gson gson = new GsonBuilder()
.registerTypeAdapter(Id.class, new IdTypeAdapter())
.enableComplexMapKeySerialization()
.serializeNulls()
.setDateFormat(DateFormat.LONG)
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.setVersion(1.0)
.create();
3. Read and Write JSON
To convert a Java object to a JSON string, use the Gson instance to call the function toJson() and pass the object.
User user = new User();
Gson gson = new Gson();
String json = gson.toJson(user);
Similarly, to convert the JSON string to a Java object, use the fromJson() method.
String json = ...;
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
4. Gson Fundamentals
In this first part, we will get to know Google Gson library and its basic mapping functionality.
- Installation – Learn to include gson dependency in the java applications using build tools like maven, Gradle or simple jar file.
- Simple Serialization and Deserialization – Learn to use GSON to serialize a simple Java Object into the JSON representation and to deserialize the JSON string to an equivalent Java object.
- Compact Vs. Pretty Printing for JSON Output Format – The default JSON output that is provided by Gson is a compact JSON format. Use the Pretty Print feature to format the JSON for reading purposes.
- Mapping of Arrays and Lists of Objects – Learn to use Google GSON library to deserialize or parse JSON, containing JSON arrays, to Java arrays or List objects.
- Mapping of Sets – Learn to use Google GSON library to deserialize or parse JSON to Set (e.g. HashSet) in java.
- Mapping of Maps – Learn to serialize HashMap using Google Gson library. Also, learn to deserialize JSON strings to HashMap containing custom Objects using Gson such that field values are copied into appropriate generic types.
5. Advance Usages
Basic examples in the first part are good enough for default usecases. We may need to customize the behavior of Gson to support specific requirements. Learn how to do this.
- Customize Gson object with GsonBuilder – For simple usecases, using
'Gson gson = new Gson();'
is enough. Learn to use GsonBuilder to create a new Gson instance with the customized configuration. - Serialize Null Values – By default, Gson omits the null values. Learn to include null values during serialization and deserialization.
- Versioning Support – Multiple versions of the same object can be maintained by using @Since annotation. Gson will ignore Gson any field/object that is greater than the configured version number.
- Custom field names using @SerializedName – Learn to use Google GSON library to serialize Java Objects into their JSON representation and to deserialize a JSON string to an equivalent Java object.
- Excluding Fields From Serialization and Deserialization – Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Learn how to use them.
- JsonReader – Streaming JSON parser – Learn to read a JSON string or file as a stream of JSON tokens.
- JsonParser, JsonElement and JsonObject – Learn to parse a JSON string or stream into a tree structure of Java objects into JsonElement.
- Custom Serialization and Deserialization – Learn to parse a JSON string or stream into a tree structure of Java objects into JsonElement.
- We can configure Gson with Spring Boot applications as the preferred JSON mapper. By default, Spring boot uses Jackson for this purpose.
- We can configure Gson with Jersey as well.
- Gson Tutorial – Recap – Let’s recap the most important topics we have learned so far.
Drop me your questions related to this gson tutorial.
Happy Learning !!
Leave a Reply