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 method
     public <T> T fromJson(String json, Class<T> classOfT)
    classOfT 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.

class Albums {
	public String title;
	public String message;
	public List errors = new ArrayList();
	public String total;
	public int total_pages;
	public int page;
	public String limit;
	List dataset = new ArrayList();
}

The Dataset class

class Dataset {
	public String album_id;
	public String album_title;
	@SerializedName("album_images")
	List<<AlbumImages> images = new ArrayList<AlbumImages>();
}

The AlbumImage clas

class AlbumImages {
	public String image_id;
	public String user_id;
	public String albumId;
}

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

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

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.

{
title: "Free Music Archive - Albums",
message: "",
errors: [ ],
total: "11259",
total_pages: 2252,
page: 1,
limit: "5",
dataset: [
{
......

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.

class Albums {
	public String title;
	public String message;
	public String[] errors = new String[]{};
	public String total;
	public int total_pages;
	public int page;
	public String limit;
}

Lets convert this to JSON and see how it looks

import com.google.gson.Gson;

public class JavaToJsonAndBack {

	public static void main(String[] args) {
		Albums albums = new Albums();
		albums.title = "Free Music Archive - Albums";
		albums.message = "";
		albums.total = "11259";
		albums.total_pages = 2252;
		albums.page = 1;
		albums.limit = "5";
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();
		System.out.println(gson.toJson(albums));
		
	}
}

This is how the resulting JSON looks like

{"title":"Free Music Archive - Albums","message":"","errors":[],
"total":"11259","total_pages":2252,"page":1,"limit":"5"}

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

public List<String> errors = new ArrayList<String>();

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

dataset: [
{
album_id: "7596",
album_title: "!!! - Live @ KEXP 7/24/2010",
......
album_images: [
{
image_id: "10574",
user_id: null,
.....
}
],
tags: [ ]

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.

class Dataset {
	public String album_id;
	public String album_title;
}

class AlbumImages {
	public String image_id;
	public String user_id;
}

Lets create a Dataset.

Dataset dataset = new Dataset();
dataset.album_id = "7596";
dataset.album_title = "Album 1";
System.out.println(gson.toJson(dataset));

the json

{"album_id":"7596","album_title":"Album 1"}

The album image

AlbumImages image = new AlbumImages();
image.image_id = "1";
System.out.println(gson.toJson(image));

The album image json

{"image_id":"1"}

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

builder.serializeNulls();

The album image json now looks like this

{"image_id":"1","user_id":null}

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

List<Dataset> dataset  = new ArrayList<Dataset>();

To the Dataset class we add a List of images

List<AlbumImages> images = new ArrayList<AlbumImages>();

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

dataset.images.add(image);
albums.dataset.add(dataset);

Here’s how our JSON looks now

{"title":"Free Music Archive - Albums","message":"","errors":[],"total":"11259",
"total_pages":2252,"page":1,"limit":"5",
"dataset":[{"album_id":"7596","album_title":"Album 1",
"images":[{"image_id":"1","user_id":null}]}]}

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.

builder.setPrettyPrinting().serializeNulls();

Here’s our formatted JSON now

{
  "title": "Free Music Archive - Albums",
  "message": "",
  "errors": [],
  "total": "11259",
  "total_pages": 2252,
  "page": 1,
  "limit": "5",
  "dataset": [
    {
      "album_id": "7596",
      "album_title": "Album 1",
      "images": [
        {
          "image_id": "1",
          "user_id": null
        }
      ]
    }
  ]
}

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

@SerializedName("album_images")
List<AlbumImages> images = new ArrayList<AlbumImages>();

our JSON now contains the name ‘album_images’

"dataset": [
    {
      "album_id": "7596",
      "album_title": "Album 1",
      "album_images": [
        {
          "image_id": "1",
     .........

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.

builder.setFieldNamingStrategy(new FieldNamingStrategy() {

			@Override
			public String translateName(Field f) {
				if (f.getName().equals("albumId"))
					return "album_id";
				else
					return f.getName();
			}
		});

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

 "album_images": [
        {
          "image_id": "1",
          "user_id": null,
          "album_id": "10"
        }

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.

public static void main(String[] args) {
		Albums albums = new Albums();
		albums.title = "Free Music Archive - Albums";
		albums.message = "";
		albums.total = "11259";
		albums.total_pages = 2252;
		albums.page = 1;
		albums.limit = "5";
		GsonBuilder builder = new GsonBuilder();
		builder.setPrettyPrinting().serializeNulls();
		builder.setFieldNamingStrategy(new FieldNamingStrategy() {

			@Override
			public String translateName(Field f) {
				if (f.getName().equals("albumId"))
					return "album_id";
				else
					return f.getName();
			}
		});
		Gson gson = builder.create();
       
		Dataset dataset = new Dataset();
		dataset.album_id = "7596";
		dataset.album_title = "Album 1";
		

		AlbumImages image = new AlbumImages();
		image.image_id = "1";
		image.albumId = "10";
		dataset.images.add(image);
		albums.dataset.add(dataset);

		System.out.println(gson.toJson(albums));

	}

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

  • October 18, 2016 at 7:16 pm
    Permalink

    For the code:
    // url is the free music archive url.
    Albums albums = gson.fromJson(IOUtils.toString(new URL(url)), Albums.class);

    “IOUtils cannot be resolved”
    There is another way?

    Reply
  • November 25, 2016 at 2:31 pm
    Permalink

    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.

    Reply
  • December 26, 2016 at 5:14 am
    Permalink

    Thank you ,,, this help me alot

    Reply
  • May 19, 2017 at 5:53 am
    Permalink

    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.”

    Reply
  • May 20, 2017 at 3:06 pm
    Permalink

    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.

    Reply
    • August 30, 2017 at 11:51 am
      Permalink

      +1
      The title is somewhat misleading.

      Reply
    • December 12, 2017 at 9:39 am
      Permalink

      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.

      Reply
  • November 25, 2017 at 8:12 am
    Permalink

    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”

    Reply
    • December 12, 2017 at 9:39 am
      Permalink

      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.

      Reply
  • April 20, 2018 at 11:12 am
    Permalink

    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? 🙁

    Reply
    • June 2, 2018 at 5:41 am
      Permalink

      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

      Reply
  • November 15, 2018 at 5:46 pm
    Permalink

    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.

    Reply
  • January 25, 2019 at 9:44 pm
    Permalink

    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);”

    Reply
  • February 26, 2019 at 1:33 am
    Permalink

    where is the way to convert JSON to a JAVA class??

    Reply

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.