Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Saturday, March 9, 2024

10 Example of Gson in Java - JSON tutorial

The Gson library is a gift from Google to Java developers. It provides the simplest but powerful mechanism to deal with JSON documents in Java. By using Gson library, you can parse JSON String to generate Java objects, serialize a Java object to create a JSON document. You can even pretty print JSON String by setting some option to the Gson class, which is the main helper class to interact with Gson library. It also provides mechanism to deal with nulls e.g. you can include null on JSON String or you can omit them. By default Gson print JSON in compact format where null fields are not exported to JSON document but null within array and list are exported. 

JSON also provides mechanism to deal with new fields added as part of code enhancement. This is known as versioning support in Gson and implemented using @Since annotation. You will see an example of this feature in coming paragraph.

Gson also provide useful annotations and settings to control the serialization mechanism i.e. you can tell Gson to exactly which fields should be included and which field should be excluded from JSON . By default, JSON doesn't include transient and static field, but you can control that behavior as well. 

Gson also provides several ways to read JSON document e.g. you can read them all in memory using JsonParser, which is similar to DOM parser of XML parsing. It creates a TreeModel in memory. This is a good way to read small JSON Strings which can fit in memory, especially in memory constrained devices like Android phones. 

Gson also provides streaming API to read large JSON files. It read the file token by token where each token represent instance of JsonToken object. This is analogous to Stax parse of XML.  So now that we know about basic and advanced capabilities of Gson libraries for dealing with JSON in Java, its time to see them in action. So let's look at the examples. 

JSON, Gson and Java Examples

In this article, I am going to share some of the common and frequently used examples from Gson library. You might know many of them if you have already used Gson before but for newbie and programmers who are new to JSON processing in Java, these examples are quite useful.

 If you want to add something on each example e.g. some useful points, feel free to do so.

For our example purpose, we will use following SmartPhone class which represent a SmartPhone:

class SmartPhone{
  private String brand;
  private String model;
  private double price;
}


How to convert Java object to JSON String?

This is known as JSON Serialization example. It's very simple to serialize a Java object to JSON string using Gson. You just need to create instance of Gson class and call the toJson() method. This method will return an equivalent JSON String for objects as shown below:

Gson gson = new Gson();
SmartPhone galaxy8 = new Smartphone("Samsung", "Galaxy 8", 829);
String JSON = gson.toJson(galaxy8);

When you print the JSON, you will see following String:

{"brand":"Samsung","model":"Galaxy 8","price":829.0}

Here is also a nice diagram about JSON is used for REST communication over HTTP. 

10 Example of Gson in Java - JSON tutorial


How to convert JSON String to Java object

The JSON DeSerialization Example is very similar to previous example with just one difference. Instead of using toJson() method you need to use the fromJson() method of Gson class and you need to pass the JSON String along with the type of the class you want to convert the JSON String into. 

Here is the code to that:

Gson gson = new Gson();
String json = "{\"brand\":\"Samsung\",\"model\":\"Galaxy 8\",\"price\":829.0}";
SmartPhone galxy8 = gson.fromJson(json, SmartPhone.class)

When you print the object, it will print following, you can verify that object's attribute has relevant values from JSON String:

SmartPhone [brand=Samsung, model=Galaxy 8, price=829.0]


How to pretty print JSON document?

By default Gson doesn't generate a pretty print JSON instead it generate JSON in compact format where there is no whitespace between key and values and there is no new line characters, but you can configure Gson to generate nicely formatted JSON as shown below:

Gson gson = new GsonBuilder().setPrettyPrinting().create();

Normal JSON:

{"brand":"Samsung","model":"Galaxy 8","price":829.0}

Pretty Print JSON:

{
"brand": "Samsung",
"model": "Galaxy 8",
"price": 829.0
}

The setPrettyPrinting() will tell Gson to format JSON String as shown above.


How to include static fields into JSON?

By default Gson exclude both transient and static fields from Serialization i.e. you will not see any keys corresponding to transient and static fields. This behavior is similar to default serialization in Java, which also avoid transient and static fields, but you can control this behavior in Gson by using excludeFieldsWithModifiers() method of GsonBuilder class. 

For example, you can tell Gson to only ignore transient fields and not static by following code:

import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.create();


How to include null fields into JSON

By default Gson doesn't include nulls in JSON document. If you want to include null fields then you need to use the option serializeNulls() as shown below:

Gson gson = new GsonBuilder().serializeNulls().create();

Now, if you convert any object using this Gson instance, it will include fields whose values are null and print null after printing fieldname. In our SmartPhone object, wallpaper is null let's see if it prints or not. 


How to use @Expose annotation in Gson?

The @Expose annotation is another way to control serialization of Java object into JSON. By using this setting, you can tell Gson that only include fields which are market by @Expose annotation while converting an object into JSON. 

You can enable this setting by using excludeFieldsWithoutExposeAnnotation() method as shown below:

Gson gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

How to serialize Array to JSON

Gson also supports serialization of a Java array into JSON. They are converted into JSON array elements as shown below:

Gson gson = new Gson();
int[] iArray = {10, 20, 30, 40, 50};
String[] stringArray = {"Gson", "Jackson", "Json-Simple"};

// Serialization
gson.toJson(iArray); // ==> [10,20,30,40,50]
gson.toJson(stringArray); // ==> ["Gson", "Jackson", "Json-Simple"]

// Deserialization
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
// ==> ints2 will be same as ints



How to use Versioning in Gson?

Gson supports versioning using @Since annotation. Let's say you have a class with 3 fields and in next version you have added one more field. Now, by using @Since annotation you can annotate each fields to the version they belong and you can configure Gson to take care of versioning using setVersion() method. Gson will only export fields with the correct version i.e. the version specified by setVersion() method. 

Gson gson = new GsonBuilder().setVersion(1.0).create();

The new field will not be included in Json if version is set to old. 


How to use Custom type Adapters in JSON

Even though Gson perform serialization and de-serializtion using its in-built adapters it is extensible to support custom type adapters as well. You can create your own adapter by extending the TypeAdapter class and pass it the type of object targeted. 

You would need to override the read() and write() method to perform your custom serialization. This is very similar to Externalizable interface, where you override readExternal() and writeExternal() method to customize default Serialization process. 


That's all about common examples of dealing with JSON in Java using Google's Gson library. From the examples, you can see that Gson is both feature rich and versatile but at the same time very easy to use. You don't need to remember too many classes, methods or annotations. 

There are only handful of important classes e.g. Gson, GsonBuilder, JsonReader, JsonParser and only a couple of annotations e.g. @Since for versioning and @Expose for controlling the serialization of fields. Though, there are more to learn about Gson and if you are keen I suggest you to take a look at the Java documentation of Gson.

Now I also have few questions for you to answer like how to serialize Collection and List to JSON and how to consume JSON from URL? If you don't know I suggest do research and read Gson documentation and if you know, its good time to show your knowledge on comment section. 

1 comment :

Anonymous said...

How am I supposed to choose between Gson and Jackson?

Post a Comment