8 minutes read

JSON (JavaScript Object Notation) is one of the most common formats for sending data over a network, writing configuration files, and saving local data in the form of key-value pairs. It is so commonly used that there are multiple JSON libraries for Java. While the Jackson JSON library is often thought of as the default Java JSON library (it's even configured by default in Spring Boot), Google's Gson library for JSON is a capable alternative. In this topic, we are going to explore how Gson makes working with JSON a breeze.

Serialization

Before we dig into Gson, let's back up for a minute and look at the big picture. What is the purpose of JSON? Why do we use it? The answer is because it helps us to serialize our data. Serialization is the process of converting data objects (in our case, Java objects) into a format that is easy to store or transfer, and can be easily reconstructed back into a data object at a later time.

JSON is not the only format for serializing objects; XML is also commonly used for that purpose. However, JSON is typically more lightweight and readable, especially when the data being formatted makes sense as a set of keys and their corresponding values.

One of the main benefits of using a universal data format like JSON or XML is that the data is readable in its serialized form. So, we don't actually need to deserialize data before viewing it and trying to understand it. We can just open the text file and start reading it.

However, if we want to do anything with the data, we will need to deserialize it. The really convenient thing is that it doesn't matter what kind of program is receiving the data. Python, JavaScript, Java, C#, you name it — they can all read a JSON file and turn the data into their own data object. In other words, the data can be deserialized into an object of any language that has objects.

Installing Gson

In this topic, we take 2.13.1 to be the most recent version, but you can always check MavenCentral for updated versions. If you are using Maven as your build tool, you can simply paste the following code into your pom.xml file's <dependencies> section.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.13.1</version>
</dependency>

If you are using Gradle as your build tool, you can use this snippet instead, placing it into the dependencies section of the build.gradle file:

implementation 'com.google.code.gson:gson:2.13.1'

Default serialization

Let's say we are building a program for a chain of music stores, and one of the many pieces of information we need to keep track of is guitar brands. So, we'll create a data object containing some basic information about guitar brands: when they were founded, their name, the country they were founded in, and a list of a few notable artists/bands who use this brand.

public class GuitarBrand {
    Date dateFounded;
    String name;
    String country;
    List<String> artistsUsedBy;
    
    // getters, setters, contructor
}

As you will see in the example below, Gson can handle dates and lists without issue. In order to illustrate how Gson handles dates, we'll begin with a SimpleDateFormat object so we can pass a real Date object into the constructor. After that, we'll create the GuitarBrand object that represents our data object. Gson takes care of the next step and converts our object into a String representing the JSON form of our guitar object. When used in this way, Gson needs to be instantiated before we call the toJson() method, passing in our object.

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

GuitarBrand espGuitar = new GuitarBrand(sdf.parse("03-08-1975"),
                                        "ESP Guitars",
                                        "Japan",
                                        Arrays.asList("Metallica", 
                                        "Children of Bodom",
                                        "The Rolling Stones", "Rammstein"));

String espGuitarJson = new Gson().toJson(espGuitar);

Viewing the results

Let's confirm that the JSON looks the way we expected. One point worth mentioning is that the JSON standard technically doesn't care about the ordering of JSON elements, because they are backed by a Map under the hood and so are accessed by key, not by their index. Some JSON libraries will change the order a bit to optimize the underlying map, however, Gson was specifically designed to keep the order intact. Here's our JSON:

{"dateFounded":"Aug 3, 1975, 12:00:00 AM","name":"ESP Guitars","country":
"Japan",
"artistsUsedBy":["Metallica","Children of Bodom","The Rolling Stones",
"Rammstein"]}

Everything looks the way it should! The date is expressed as a String using Gson's default date formatting. This can of course be customized if you need it to be expressed in a particular format. The List we passed in to keep track of the artists is represented by a JsonArray.

By default, Gson will not serialize object properties that have a value of null. You must explicitly set Gson to force serialization of null values (see our topic on custom serialization).

Default deserialization

If we store or transmit data in JSON, we are going to need a way to read the data back into our Java program as an object. Gson makes this very easy to do. You can see how simple it is in the following example. Let's assume that the variable jsonInput holds the JSON String from the previous example.

GuitarBrand espGuitar = new Gson().fromJson(jsonInput, GuitarBrand.class);

Voilà! We now have our original GuitarBrand object back.

Conclusion

JSON is one of the preferred formats for serializing data. The Gson library makes working with JSON much easier for Java developers. Gson can serialize our data by converting Java objects into a String representation of its corresponding JSON, which can then be written to a file or sent over a network. When given the JSON representation of a Java object, Gson can also deserialize it back into a Java object to use in your program.

62 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo