Java Gson – Convert JSON string to a java object

Google json provides methods to convert a JSON string to a Java object. Gson uses the name to match the json property to the java field. There are two ways to convert json to java.

  1. Using the com.google.gson.Gson class. Create a new instance of this class and use the methodclassOfT is the java object to which the json is to be converted to.
  2. The other way is to use the com.google.gson.GsonBuilder class. This class allows setting up certain features, such as – allowing null serialization or setting up custom serializing policies. Create a GsonBuilder, apply the features and then obtain the Gson class from the builder.

Let’s look at an example. For this example we consider java objects of non generic type only

Part A : Converting JSON to a java object

In this example we use the Gson library to de-serialize json from free music archive. We need a java class that mimics the structure of the json image. In the second half of the tutorial we will see how to build that java class, but for now, let’s assume that we have a Java class that corresponds to the JSON structure. The main class is the Albums class and it contains the list of Datasets. Each Dataset is one album.

The Dataset class

The AlbumImage clas

Here’s the main method that shows how GSON can convert the album JSON string to a java object.

Part B : Building the Java class corresponding to the JSON string

In Part A, we converted the JSON string to a java object. However, how do we build the java object in the first place? Lets see this in action. If you look at the JSON, it starts with a root object that has properties such as title, message, errors, etc.

Lets ignore the dataset for now. Lets just build a java class to hold the root. We call that class Albums. We will make the fields public for brevity, but you might want to make them private and use setters.

Lets convert this to JSON and see how it looks

This is how the resulting JSON looks like

This is a good beginning. Notice how we initialized errors to an empty array. Otherwise Gson would think its null and either ignore it or print null if we allow null serialization. In this case, it looks like we are better off with using a List for errors. Lets change the errors variable to

We have used a GsonBuilder since that allows us to customize the conversion. we will see its benefit later in the example. The next step is to build a class for the dataset. Lets see how the dataset JSON looks

For this tutorial we will be considering only some fields from ‘dataset’ and ‘album_images’. The other fields can be added similarly. The dataset contains an array of album and each album contains, besides other fields, an array of album_images. We build a java class for each JSON object. We have already built a java class for albums. Now lets built classes for dataset and album_image.

Lets create a Dataset.

the json

The album image

The album image json

See how gson has not printed user_id since its null. We need to be able to tell json to serialize null fields too. GsonBuilder helps us do that

The album image json now looks like this

Lets now wire up the dataset into the albums class and the AlbumImage into the dataset class. To the Albums class we add the List of Dataset

To the Dataset class we add a List of images

Lets change the main method to add dataset to the album and image to the dataset

Here’s how our JSON looks now

Lets turn on pretty printing so that our JSON looks better. However, we do that only during developement. If you are actually designing a server that provides JSON data, then make the JSON as compact as possible.

Here’s our formatted JSON now

This looks good, however we want to change the name of the ‘images’ element in dataset to ‘album_images’. Lets assume we cant change the java name because it follows the java naming policy. We can use annotation on the field to specify the json name to use for a particular java property. Here’s how to do that

our JSON now contains the name ‘album_images’

If you dont want to bind your java class to GSON then there is another way to do this. Lets add one more field to the AlbumImage class. We call it albumId. However, we want to name the field album_id in the JSON. To do that we need to specify a NamingStrategy in the GsonBuilder.

The translateName method is called for all fields and if the name matches albumId we convert the name to album_id and send it back otherwise we send the default. the album_images element now looks like this

GsonBuilder provides a lot of other customization. You can disable HTML escaping, exclude fields with specific modifiers (e.g. exclude all protected fields), set custom type adapters, set exclusion policies etc. Look at the GsonBuilder JavaDoc for the complete list. You can now use the Albums class and parse the JSON using the fromJson method (you will have to add the other properties) as shown in part A.

Part C : Java to JSON

While we are here, Let’s now use GSON library to create json from the Java object that we just built.

16 thoughts on “Java Gson – Convert JSON string to a java object

    1. IOUtils is from apache commons. If you cant use apache commons, just try the traditional methods to download the file using Java IO.

  1. Great intro tutorial…enough detail to be actionable, and avoiding so much detail that the salient points are obfuscated and difficult to discern. But can you please explain line #17 of the final Albums class? I don’t understand the closing dataset and string elements.

  2. Please correct the following statement,
    from
    “The dataset contains an array of album and each album contains, besides other fields, an array of album_images.”
    to
    “The album contains an array of dataset and each dataset contains, besides other fields, an array of album_images.”

  3. So, the title of the post is “Convert json to a java object ” but the whole tutorial explains how to convert Java objects into their Json representation.

    1. That is the approach that we are trying to put forward. When you are working on a problem to convert JSON to a Java object, the best way to start is to work the other way round. i.e. create a Java object such that the resultant JSON is identical to the JSON that you are trying to parse.

  4. This doesn’t do what it says, while otherwise it’s a good article. Title should be “parse java objects to json string”. And wherever you use “deserialize” it should be “serialize”

    1. That is the approach that we are trying to put forward. When you are working on a problem to convert JSON to a Java object, the best way to start is to work the other way round. i.e. create a Java object such that the resultant JSON is identical to the JSON that you are trying to parse.

  5. This tutorial just shows how to parse java objects to JSON.

    Do you have a tutorial on how to parse JSON to java objects or it this article just kind of a lie? 🙁

    1. We explain this at the beginning of the tutorial, but to reiterate : The way to approach the problem of deserialization is to build a java class such that the when Gson converts the Java class to JSON, the resultant JSON resembles the one we are trying to parse

  6. This would be very useful if it did relate to the title as other commenters have noted. (Please don’t repeat your “approach” statement) Given your approach, this is the first half; now please show the example of reading the created objects from a JSON String.

  7. I think the section here shows how to do the reverse, i.e. converting from JSON to a java object, which others were talking about:

    “GsonBuilder provides a lot of other customization. You can disable HTML escaping, exclude fields with specific modifiers (e.g. exclude all protected fields), set custom type adapters, set exclusion policies etc. Look at the GsonBuilder JavaDoc for the complete list. You can now use the Albums class and parse the JSON using the fromJson method (you will have to add the other properties)

    1 // url is the free music archive url.
    2 Albums albums = gson.fromJson(IOUtils.toString(new URL(url)), Albums.class);”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top
Bitnami