Simple GSON Example

1 year ago by in Articles, GSON, Introduction Tagged: ,

GSON is a Java API, developed by Google, used to convert between Java objects and JSON objects. This article discusses and provides simple code examples using this API. More information about this API can be found at: http://sites.google.com/site/gson/.

This is the first article from a series of articles about GSON. No GSON or JSON experience is required as this article acts as a primer for the other articles. The second article provides more examples about the use of GSON deserializer (from JSON to Java) and the third article provides more examples about the GSON serializer (from Java to JSON).

All code listed below is available at: https://java-creed-examples.googlecode.com/svn/gson/Simple%20Gson%20Example. Most of the examples will not contain the whole code and may omit fragments which are not relevant to the example being discussed. The readers can download or view all code from the above link.

The reader needs to have a basic knowledge of Java (tutorial) and a very basic knowledge of Maven (Homepage). The code listed here makes use of maven to download the GSON library. Checking out the project into Springsource Tool Suite (the recommended IDE) will work without having to configure anything.

Download and Install

Before you can do any work with this API, you need to download the library (jar file) and include it in the classpath. The library, together with the source and JavaDocs, can be downloaded from: http://code.google.com/p/google-gson/downloads/list. Once downloaded, add the gson-<version>.jar to the classpath. For those readers who prefer to use Maven to manage the dependencies (JAR files), add the following dependency to the pom.xml.

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

Change the <version>2.2.4</version> as required. All code examples shown in this article use the version listed above. A copy of the pom.xml file can be found here.

If this library is to be used in a web application, make sure to have a copy saved under the WEB-INF/lib folder. Alternatively, the library can be added to the application server and made available to the web application.

A Simple Example

The GSON API provides a class, Gson (Java Doc), that handles the conversions between Java and JSON objects. An instance of this class can be created by invoking the default constructor or as shown in the simple example below, using the GsonBuilder (Java Doc) class. The GsonBuilder class provides customisation and allows the developer to instantiate Gson as required.

package com.javacreed.examples.gson.part1;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleExample1 {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().create();
        gson.toJson("Hello", System.out);
        gson.toJson(123, System.out);
    }
}

In the above example, we’ve created an instance of Gson and converted the Java String and int to JSON objects. The above code produces the following as its output to the command prompt:

"Hello"123

It’s not rocket science, but it’s a start. Note that the output of the above is all going to the command prompt. The toJason() method takes two parameters, the Java object to be converted to JSON and an instance of Appendable (Java Doc). We can easily change the out to a file or network stream.

package com.javacreed.examples.gson.part1;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleExample2 {
    public static void main(String[] args) throws IOException {
        Writer writer = new FileWriter("Output.json");

        Gson gson = new GsonBuilder().create();
        gson.toJson("Hello", writer);
        gson.toJson(123, writer);

        writer.close();
    }
}

Observation

Why is the variable declared as a Writer when the actual type is FileWriter?
It is a good practice to have your variables as generic as possible. In the above example, we’re only using methods defined by the Appendable and Writer interfaces. Having the variable type more specific than required will make the code less portable and harder to maintain as we’ll see in the following example.

Note that in the above example we are not handling the steams (Writer) properly. Ideally the resources are closed within the finally block (tutorial) or used within the try-with-resources (tutorial) as shown below. We’ve ignored this to keep the code as simple as possible.

public static void main(String[] args) throws IOException {
    try (Writer writer = new FileWriter("Output.json")) {
        Gson gson = new GsonBuilder().create();
        gson.toJson("Hello", writer);
        gson.toJson(123, writer);
    }
}

The above code produces the file: Output.json with the JSON objects. Note that here we used the character streams and not the byte streams. We cannot use the byte streams as the toJson() method is expecting an Appendable instance and the byte streams are not descendants of the Appendable interface. The Appendable interface works with characters and not bytes. Java provides the InputStreamReader (Java Doc) and the OutputStreamWriter (Java Doc) classes that convert byte streams into character streams as illustrated in the following example.

Observation

Note that when using the InputStreamReader and the OutputStreamWriter classes, make sure to provide the encoding or character set as otherwise the platform default will be used. This will make your code less portable and may produce errant behaviour is executed from another platform.

package com.javacreed.examples.gson.part1;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleExample3 {

    public static void main(String[] args) throws IOException {
        try(Writer writer = new OutputStreamWriter(new FileOutputStream("Output.json") , "UTF-8")){
            Gson gson = new GsonBuilder().create();
            gson.toJson("Hello", writer);
            gson.toJson(123, writer);
        }
    }
}

As you can see, we only needed to change the instantiation part. The rest (expect for the imports) of the code is unchanged. This is one of the benefits of using interfaces instead of classes as variables types.

Consuming JSON objects

Let’s say that we need to consume JSON objects and load them as Java objects. Assume that a web server will produce the following JSON when queried:

{
  NAME:"Albert Attard",
  P_LANGUAGE:"Java",
  LOCATION:"Malta"
}

This JSON object contains three fields with their respective values. Let’s say that we need to consume the JSON object and create a Java object that represents this data. To make this example more interesting, let assume that we’re only interested in the name and the location fields.

First we need to create a Java class with the fields that we want to represent (name and location). Let’s call the class Person. The name of this class is irrelevant, but the names of the fields are not. The field names must match (including the case) with the names in JSON. Furthermore, the class must include a default constructor (even in this is set as private). As shown below, the fields name and location are in uppercase as found in JSON. The JSON field P_LANGUAGE is ignored as the Java object does not include a field with this name. It is understandable that the fields’ names do not follow the Java naming convention, but for the time being let’s keep things simple. More about this is discussed in part 2.

package com.javacreed.examples.gson.part2;

public class Person {
    private String NAME;
    private String LOCATION;

    // Getters and setters are not required for this example.
    // GSON sets the fields directly using reflection.

    @Override
    public String toString() {
        return NAME + " - " + LOCATION;
    }
}

With the Java object ready, we can read the JSON objects and load them as Java objects as illustrated below. To simulate a real life situation, we’re using a byte stream as input. Also note that the JSON content is saved into a file (which is not usually the case) located in the resources source folder.

package com.javacreed.examples.gson.part2;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonToJava {

    public static void main(String[] args) throws IOException {
        try(Reader reader = new InputStreamReader(JsonToJava.class.getResourceAsStream("/Server1.json"), "UTF-8")){
            Gson gson = new GsonBuilder().create();
            Person p = gson.fromJson(reader, Person.class);
            System.out.println(p);
        }
    }
}

This should produce the following:

Albert Attard - Malta

Gson parsed the JSON object and created an instance of the Person class which is then printed to the command prompt.

Nested JSON Objects

Let’s take the above example one step further and include a nested object as illustrated in the following JSON code fragment.

{
  NAME:"Albert Attard",
  P_LANGUAGE:"Java",
  LOCATION:"Malta",
  EXAM: {
    SUBJECT:"Programming",
    GRADE:4.5
  }
}

Here we have an EXAM field which is made from two other fields: SUBJECT and GRADE. Likewise, we need to modify the Person class defined above to include the EXAM field and create a new Java class to represent this field which will contain the SUBJECT and GRADE fields.

We first create the new class that will represent the nested object. As we discussed before, the class name is irrelevant but the fields’ names must match those define in JSON.

package com.javacreed.examples.gson.part3;

public class Exam {
    private String SUBJECT;
    private double GRADE;

    // Getters and setters are not required for this example.
    // GSON sets the fields directly using reflection.

    @Override
    public String toString() {
        return SUBJECT + " - " + GRADE;
    }
}

Now we can modify the Person class and include a new field with the same name as in JSON of type Exam as shown next. Note that the following Person class in found in a different package from the previous one.

package com.javacreed.examples.gson.part3;

public class Person {

    private String NAME;
    private String LOCATION;
    private Exam EXAM;

    @Override
    public String toString() {
        return NAME + " - " + LOCATION + " (" + EXAM + ")";
    }
}

Note that the changes required are minimal as Gson dynamically discovers (through reflection) the class and its fields. This article does not cover reflection. For more information about reflection please refer to: Reflection in Action.

Finally, let’s try the new changes out.

package com.javacreed.examples.gson.part3;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonToJava {

    public static void main(String[] args) throws IOException {
        try(Reader reader = new InputStreamReader(JsonToJava.class.getResourceAsStream("/Server2.json"), "UTF-8")){
            Gson gson = new GsonBuilder().create();
            Person p = gson.fromJson(reader, Person.class);
            System.out.println(p);
        }
    }
}

No changes were made to the class JsonToJava as Gson used our model (the Person and Exam classes) to map Json to Java.

Conclusion

Even though it may be a new concept, JSON is very simple and straight forward. Furthermore, it is gaining popularity over the more cumbersome XML which inflates the message/data exchanged by the added XML tags. It is good to point out that JSON is a subset of JavaScript which makes it a perfect candidate for exchanging data with JavaScript based applications such as web pages. The GSON API makes it very easy to use and even though not discussed here, it provides a great deal of flexibility.

For more GSON examples please visit the second part, where we explore more complex examples and discuss how to use the GSON deserializer to take full control over the deserialization process.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 SearchSecurity.co.UK award (Website).

17 Responses to “Simple GSON Example”


Wyatt
December 26, 2012 Reply

Your post, Simple GSON Example | JAVACREED.com, is really well written and insightful. Glad I found your website, warm regards from Wyatt!

Fernanda
April 15, 2013 Reply

Hi Albert!

Could the Exam1 object be a Hash Map? For example, in this case, the property “attributes” could be a Hash Map where the first item would be the key e the second a value?

{“feature” : [{ “attributes” :{ “srid” : 1010101, “type” : “Point”},
“coordinates” : [182176.64924999999,
1679006.5104055556]
}]
}

Thanks!

Albert Attard Albert Attard
April 15, 2013 Reply

Yes, but not using the examples above as these are very simple and do not allow you to manipulate JSON as you need. I recommend the following article: Gson Deserialiser Example, which describes how you can manipulate JSON as required. You can find the code examples in the SVN Repository

Hope this helps. If not, please send again.

Tom Yu
June 17, 2013 Reply

Awesome info but I really dislike your green header bar. It takes up so much vertical space which makes it harder to digest the content.

Albert Attard Albert Attard
June 18, 2013 Reply

How would you do it?

Irwanto
September 6, 2013 Reply

hello, i’ve problem. my json field is numeric. so i can’t create variable with numeric name. please help me. thank you :)

Albert Attard Albert Attard
September 7, 2013 Reply

You have two options:

Hope these solve you problem. If not, post again.

Sebastian Cheung
November 3, 2013 Reply

How to run these gson samples in STS after I have done a ‘Check Out’? Cannot seem to config to run any of the samples? Help is appreciated. Thanks a lot for your tutorials.

Albert Attard Albert Attard
November 3, 2013 Reply

Can you please give me the name of the project you checked out?

Sid
January 13, 2014 Reply

This is a very neat way to do things.
But what if I have a JSON array of data objects?
Can I get a set or list of data objects?

Albert Attard Albert Attard
January 13, 2014 Reply

Thank you.

I recommend you read another article about GSON titled: Gson Deserialiser Example. In this article you will find more complex examples about GSON including arrays.

James
August 1, 2014 Reply

Hi Albert,
I am a little lost with this – gson.toJson(“Hello”, writer);

In my JSON object there were no initial name value pair so what I am writing to the file ?

Am I missing something here ?

Regards,
James

Albert Attard Albert Attard
August 4, 2014 Reply

Thank you for your feedback James.

You are right, the output shown in the first example is not a valid JSON. The aim of that example was to get things started and to show the readers various ways to produce JSON strings and to output these to different targets (such as: Streams, Files etc.). I will update the text to make sure I say that this is not a valid JSON, so that this example does not confuse future readers in thinking that "hello"123 is a valid JSON string.

Regards,
Albert

J-key
August 6, 2014 Reply

Hi.

I have a question. This is my TestVO.

class TestVO{
   String a;
   String b;
   
   public Sring toString()
   {
      return "TestVO[ a=" + a + ", b=" + b +"]";
   }
}

and then, in controller its value like [ TestVO[a = "test1", b="test2"], TestVO[a="111", b="222"] ]

I don’t know how can I transform it to ArrayList using Gson

please anwser me :)

Albert Attard Albert Attard
August 6, 2014 Reply

Please note that the String: “[ TestVO[a = "test1", b="test2"], TestVO[a="111", b="222"] ]” is not a valid JSON, thus cannot be parsed using Gson. Please refer to the website: http://json.org/ for more information about JSON strings.

You can change the toString() method to return the following: "['a':'" + a + "', 'b':'" + b +"']" instead or use a TypeAdapter as described in the article: Gson TypeAdapter Example.

Hope this helps.
Albert

J-Key
August 7, 2014 Reply

Thank for your answer!

Yogesh
August 24, 2014 Reply

Thanks for this tutorial.

Leave a Comment



nine + = 10