Skip to content

Gson – Convert Java object to JSON example

Gson – Convert Java object to JSON example shows how to convert a Java object to JSON using the Gson library in Java. This example also shows how to include null fields in the JSON data that are not included by default.

How to convert a Java object to JSON?

The Gson library provides methods to serialize and deserialize Java objects to and from JSON data. For converting a Java object to JSON, we can use the toJson method of the Gson class.

The toJson method serializes the given Java object to a JSON format. In the below given example, I am going to serialize Employee class objects to JSON using this method.

Output

As you can see from the output, both of the objects are serialized in the JSON representation. However, by default, the toJson method skips the null fields. As it happened with our second employee object, the Designation field was not serialized because it was null.

To include null fields in the JSON, we need to create the Gson object using GsonBuilder class and call the searializeNulls method.

This method allows us to serialize null fields that are omitted by default. Let’s do that and run the program again.

Output

As we can see, the Designation field is serialized even though it is specified as null.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.