Gson Tutorial

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 or static 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.

Drop me your questions related to this gson tutorial.

Happy Learning !!

Download Sourcecode

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial