Gson – Quick Guide

Gson (by Google) is a Java library that can be used to convert a Java object into JSON string. Also, it can used to convert the JSON string into equivalent java object.

There are some other java libraries also capable of doing this conversion, but Gson stands among very few which does not require any pre-annotated java classes OR sourcecode of java classes in any way.

Gson also support the old java classes which had not support of generics in them for type information. It just work with these legacy classes smoothly.

In this gson tutorial, I am giving few examples of very common tasks you can perform with Gson.

Table of Contents

1. Prerequisites and dependency
2. Create Gson object
3. Convert Java objects to JSON format
4. Convert JSON to Java Objects
5. Writing an Instance Creator
6. Custom Serialization and De-serialization
7. Pretty Printing for JSON Output Format
8. Versioning Support
9. More Gson Tutorials

1. Prerequisites and dependency

1.1. POJO Class

Before coming to examples, let’s have a POJO class which we will use in given examples.

public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;
   
   public Employee(){      
   }
   
   public Employee(Integer id, String firstName, String lastName, Date birthDate){
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
   }
   
   //Getters and setters
   
   @Override
   public String toString()
   {
      return "Employee [id=" + id + ", firstName=" + firstName + ", " +
            "lastName=" + lastName + ", roles=" + roles + "]";
   }
}

1.2. Maven dependency

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

In gradle, use below dependency.

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

2. Create Gson object

Gson object can be created in two ways. First way gives you a quick Gson object ready for faster coding, while second way uses GsonBuilder to build a more sophisticated Gson object.

//1. Default constructor
Gson gson = new Gson();

//2. Using GsonBuilder
Gson gson = new GsonBuilder()
			 .disableHtmlEscaping()
			 .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
			 .setPrettyPrinting()
			 .serializeNulls()
			 .create();

When using GsonBuilder, there are plenty of other useful options you can provide to Gson object. Go ahead and check them out.

3. Gson toJson() – Convert Java object to JSON String

To convert object to json, use toJson() method.

Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));

Gson gson = new Gson();

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

Program Output.

{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}

4. 3. Gson fromJson() – Convert JSON string to Object

To parse json to object, use fromJson() method.

Gson gson = new Gson();

System.out.println(
	gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER']}", 
	Employee.class));

Program Output.

Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER]]

5. Gson InstanceCreator – when no-args constructor is not present in given object

In most of the cases, Gson library is smart enough to create instances even if any class does not provide default no-args constructor. But, if you found any problem using a class having no-args constructor, you can use InstanceCreator support. You need to register the InstanceCreator of a java class type with Gson first before using it.

For example, Department does not have any default constructor.

public class Department
{
   public Department(String deptName)
   {
      this.deptName = deptName;
   }

   private String deptName;

   public String getDeptName()
   {
      return deptName;
   }

   public void setDeptName(String deptName)
   {
      this.deptName = deptName;
   }
   
   @Override
   public String toString()
   {
      return "Department [deptName="+deptName+"]";
   }
}

And our Employee class has reference of Department as:

public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;
   private Department department; //Department reference
   
   //Other setters and getters
}

To use Department class correctly, we need to register an InstanceCreator for Department as below:

class DepartmentInstanceCreator implements InstanceCreator<Department> {
   public Department createInstance(Type type)
   {
      return new Department("None");
   }
}

Now use the above InstanceCreator as below.

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator());

Gson gson = gsonBuilder.create();

System.out.println(
            gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta',
            'roles':['ADMIN','MANAGER'],'department':{'deptName':'Finance'}}", 
            Employee.class));

Program Output.

Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], department=Department [deptName=Finance]]

6. Gson custom serialization and deserialization

Many times, we need to write/read the JSON values which are not default representation of java object. In that case, we need to write custom serializer and deserializer of that java type.

In our example, I am writing serializer and deserializer for java.util.Date class, which will help writing the Date format in “dd/MM/yyyy” format.

6.1. Gson custom serializer

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class DateSerializer implements JsonSerializer<Date>
{
   private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
   public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context)
   {
      return new JsonPrimitive(dateFormat.format(date));
   }
}

6.2. Gson custom deserializer

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;

public class DateDeserializer implements JsonDeserializer<Date>
{
   private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
   public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context)
   {
      try
      {
         return dateFormat.parse(dateStr.getAsString());
      } 
      catch (ParseException e)
      {
         e.printStackTrace();
      }
      return null;
   }
}

6.3. Register custom serializer and deserializer

Now you can register these serializer and deserializer with GsonBuilder as below:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());

6.4. Gson custom serializer and deserializer example

Complete example of serializer and deserializer is as below.

Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));
employee.setBirthDate(new Date());

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
Gson gson = gsonBuilder.create();

//Convert to JSON
System.out.println(gson.toJson(employee));

//Convert to java objects
System.out.println(gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta',
                                 'roles':['ADMIN','MANAGER'],'birthDate':'17/06/2014'}"
							           , Employee.class));
							

Program Output.

{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"],"birthDate":"17/06/2014"}

Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], birthDate=Tue Jun 17 00:00:00 IST 2014]	

7. Gson setPrettyPrinting() – pretty print JSON output

The default JSON output that is provide by Gson is a compact JSON format. This means that there will not be any white-space in the output JSON structure. To generate a more readable and pretty looking JSON use setPrettyPrinting() in GsonBuilder.

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(employee);

Program Output.

{
  "id": 1,
  "firstName": "Lokesh",
  "lastName": "Gupta",
  "roles": [
    "ADMIN",
    "MANAGER"
  ],
  "birthDate": "17/06/2014"
}

8. Gson setVersion() – versioning support

This is excellent feature you can use, if the class file you are working has been modified in different versions and fields has been annotated with @Since. All you need to do is to use setVersion() method of GsonBuilder.

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());

//Specify the version like this
gsonBuilder.setVersion(1.0);

Gson gson = gsonBuilder.create();

8.1. Fields added in various versions in Employee.java

public class Employee
{
   @Since(1.0)
   private Integer id;
   private String firstName;
   private String lastName;
   
   @Since(1.1)
   private List<String> roles;
   
   @Since(1.2)
   private Date birthDate;
   
   //Setters and Getters
}

Gson @Since example

//Using version 1.0 fields
gsonBuilder.setVersion(1.0);

Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta"}

/////////////////////////////////////////////////////////////

//Using version 1.1 fields
gsonBuilder.setVersion(1.1);

Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}

/////////////////////////////////////////////////////////////

//Using version 1.2 fields
gsonBuilder.setVersion(1.2);

Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"],"birthDate":"17/06/2014"}

9. More Gson Tutorials

  1. Gson – GsonBuilder Tutorial
  2. Gson – Serialize and deserialize JSON
  3. Gson – Serialize and deserialize Map
  4. Gson – Serialize and deserialize Set
  5. Gson – Serialize and deserialize array
  6. Gson – @SerializedName annotation example
  7. Gson – Jersey + Gson Example

That’s all for this very useful java gson library to convert java objects from /to JSON. Drop a comment is you have any query or feedback.

Happy Learning !!

Reference

GSON User Guide

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

29 thoughts on “Gson – Quick Guide”

  1. hello
    i have a issue, when i convert “gson.toJson(jObj);” then it add \r\n in the response.
    i do not want \r\n in my response .

    How to resolve it.

    Thanks,
    Jon

    Reply
  2. Some great code examples on various usage of Gson! However, I’ve come across a Json payload I need to parse which contains JSON Arrays which I don’t want, only the Objects. How do I parse a json file and exclude the JSON Arrays?

    This is what I used with my JSON Objects:

    Type type = new TypeToken<Map<String, MyPOJO>>(){}.getType();
    Map<String, MyPOJO> myMap = gson.fromJson(JSONString, type);
    

    But whenever it comes across an Array, it crashes with “Expected BEGIN_OBJECT but was BEGIN_ARRAY”

    This is my JSON:

    {  
       "1002001":{  
          "level":2,
          "name":"CaptKrunch",
          "uid":1002001,
          "user":{  
             "age":21,
             "chat_color":"CC3299",
             "city":"None",
             "country":"United States",
             "creation":1269969663
          },
          "meta":{  
             "score":1762.000,
             "flags":6176,
             "kbit":0,
             "lastnews":1459736973,
             "rank":78
          }
       },
       "1003001":{  
          "level":11,
          "name":"LtRaine",
          "uid":1003001,
          "user":{  
             "age":35,
             "chat_color":"FFAABB",
             "city":"LA",
             "country":"United States",
             "creation":1269369663
          },
          "meta":{  
             "score":11562.000,
             "flags":1176,
             "kbit":2048,
             "lastnews":1279736973,
             "rank":11
          }
       },
       "tags_1002001": [
         "mage",
         "quick",
         "conqurer",
         "almighty"
       ]
    }
    

    (this is just a small snippet, there can be hundreds of “tags_####” arrays and objects)

    Any pointers on how to parse the JSON and exclude the Arrays greatly appreciated!

    Reply
  3. Nice article! I have a basic question if anyone can please answer –
    What is the advantage of having corresponding Java classes for JSON response? When we can read and write using JSON libraries. Im not able to figure out exactly why it is needed.
    Any example or link along will be helpful
    Thanks

    Reply
    • All such libraries do one common thing – they convert between java classes and JSON. In fact, you asked the opposite question – in any java program, you have java classes anyway whether you have JSON or not … question should be why you need JSON?? And answer is that JSON is absolutely optional, you can use XML or even serialize the java objects. All works same.

      Reply
  4. First of all Thank you for GSON article. I am beginner. This article give me fair understand for GSON.I have to deserialize below json data to Java Object.
    I am able to parse name and phoneNumber fields. But for the field “deparments”, i am getting Null. Can you please help me, how to parse this?

    Json data:
    {
    “name”: “customer”,
    “phoneNumber”: “000000000”,
    “deparments”: “xyz,abc,wyz,djkf, iii”
    }

    CustomerInfo.java
    public class CustomerInfo
    {
    private String name;
    private String phoneNumber;
    Private String deparments;

    // gettters and setters
    }

    Reply
  5. Hey Lokesh very nice tutorial. Can you put some light on how to convert dicom image metadata into JSON format. So that i can store it in mongodb.

    Reply
  6. Hello Lokesh! First of all, thank you for your tutorial.
    I have two question regarding the fields naming in java object.
    I have a class, in which all fields there is a ‘m’ prefix.
    Second, does the name of the field must match with the name in the json object?
    Thank you!

    Reply
  7. Hello Lokesh,
    thanks a lot for such an informative and helpful article.
    I’m trying to build an android application which needs to pass device information to a custom server and receive some from the server(presently chosen simple socket programming and json objects). can you please suggest suitable library for implementing this communication….i’m a newbie and forsee number of complications in implementing this.
    Thanks!

    Reply
  8. hi.. All,

    I am getting DB table column names and data by using hibernate but, i am not able to display out put like this below.
    I have to display out put like this below format (out put should be in JSON format) please give me some solutions or advises how i can achieve this.

    Required Out Put
    ——————————–
    {
    “Table :”[
    {
    “header”:”EmpID”, “EmpName”
    }
    {
    “Body” : [
    {
    “row 0 ” : “123”, “ABC”
    “row 1 ” : “456”, “XYZ”
    }
    ]
    }
    ]
    }

    Thanks in Advance

    Reply
  9. i want to generate json with xml tags in it as below:

    {
    “title”: “Welcome”,
    “body”: <esi:include src='/some_url/userid' /> 
    }

    Please note that the value of attribute body is not enclosed in double quotes. is there a way to generate such json respnse?

    Reply
  10. hey.
    Thank’s for this nice tutorial.
    I’ve had a bit of a problem, and I was wondering if you could help me with it .
    Here’s a json I want to parse through java :

    {“id”:1,”result”:{“gid”:”1″,”type”:”L”,”help”:”Veuillez entrer votre niveau d’\u00e9tudes \u00e0 l’INPT.”,”language”:”fr”,”sid”:”796246″,”question_order”:”3″,”question”:”\r\n\tvotre niveau d’\u00e9tudes \u00e0 l’INPT :\r\n”,”answeroptions”:{“A1”:{“answer”:”INE1″,”assessment_value”:”0″,”scale_id”:”0″},”A2″:{“answer”:”INE2″,”assessment_value”:”1″,”scale_id”:”0″},”A3″:{“answer”:”INE3″,”assessment_value”:”1″,”scale_id”:”0″}}},”error”:null}

    The problem I encounter is with the “answeroptions” parameter : I declared it in my class as an array but it generates errors saying it encountered an object.
    How could I parse without loosing generality : I want tp create a methode that can parse it regardless of how many A1,A2,…An elements there are in it.
    Thanks in advance mate

    Reply
      • Yes I know, but the “answeroptions” come as an object, however there’s no way to know how many A1, .. An objects there are so I don’t know how my class should look like.

        Reply
        • It’s very interesting question. Thanks for putting it here.
          First of all, A1, .. An are not going to be parsed as array; simple reason because all elements in array or list must share same KEY in JSON.
          I believe that the structure you need to follow is :

          AnswerOptions {
          Answer A1;
          Answer A2;
          Answer A3;
          Answer A4;
          }

          Looking at the kind of response, I do not thing there will be more than some finite options (my guess 5-6) will be there. Also, you can take help of ”question_order”:”3″. May be there is more information you can get in response which can be referred as number of options.

          Moreover, all above analysis is pure guess work as I don’t have any idea of work you are trying to do with this JSON. Still. I will fight hard to get a solution for you, generic one.

          Reply
          • Thank you.
            As a matter of fact this was my very first answer.
            The Json I get is from LimeSurvey, a php framework to create surveys, this json answer gives me the properties of a definite question, however the number of answer options in virtually infinte in LimeSurvey .. Thank’s a lot for your help and this great tutorial, if you could find a generic answer it will be awesome, if not I’ll just have to fix a maximum number of Answers.
            Thank’s again

          • I have found a Way to do it.
            I just declare “answeroptions” as

             Map<String,Answer> answeroptions;   

            and everything goes according to plan, I don’t have to care for how many Ai there are.
            Thank you for everything

  11. Hello Lokesh,Thanks for the gson article provided by you.I think we need Json when we are using any graphs or hierarchical structures,

    Please let me know the real-time scenarios when we can use the json and gson

    very nice article as usual.

    Thanks

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.