Thursday, September 10, 2015

How to convert JSON to / from Java Object (Pojo) using GSON


JSON is stand for JavaScript Object Notation. It is light wight interchange format used over network communication between client and server. It is easy for human to read and write because it is in simple Text format. JSON is completely language independent.

In this article i will show you how to convert Java Object into JSON notation using GSON Library.
You can Download Gson Library here Or you can add dependency in your pom.xml as show below
        <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
       </dependency>

JSON contain two types of structure

  1. A collection of the Key:Value pair which is referred as Json Object. For Example : {"Key":"Value"} 
  2. Collection of value in form of list which is referred as Json Array. For Example : {"Array":["1","2","3"]}
For this article we need to now only two function in GSON library
  1. toJson() - Convert your Java object into Json format.
  2. fromJson() - Convert your Json string to Java Object. 

Java Pojo Class
             
Here is my Java Bean class with construction which is used to initialize value to my bean class object later this class will be used to convert into JSON format.

package com.java.gson;
import java.util.List;

public class MyBeanClass
{
       int srNo;
       String name;
       List<String> list;
      
       public MyBeanClass(int srNo,String name,List<String> list) {
             this.srNo = srNo;
             this.name = name;
             this.list = list;
       }
      
       public int getSrNo() {
             return srNo;
       }
       public void setSrNo(int srNo) {
             this.srNo = srNo;
       }
       public String getName() {
             return name;
       }
       public void setName(String name) {
             this.name = name;
       }

       public List<String> getList() {
             return list;
       }

       public void setList(List<String> list) {
             this.list = list;
       }
     
      @Override
       public String toString() {
             return "Data : [srno : "+srNo+", name : "+name+", list : "+list+"]";
       }
}

toJson() Example 

In this example we will see that how java object will be converted into JSON string. You may store or save this into file or passed this string across network. 

package com.java.gson;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

public class JsonExample
{
       public static void main(String[] args)
       {
             List<String> list = new ArrayList<String>();
             try
             {
                    list.add("Json");
                    list.add("Gson");

                    MyBeanClass myBean = new MyBeanClass(1, "Java",list);

                    Gson json = new Gson();
                    String jsonStr = json.toJson(myBean);

                    System.out.println(jsonStr);
             }
             catch(Exception ex)
             {
                    ex.printStackTrace();
             }
       }
}

In above example json.toJson(myBean) is used to convert your Java bean class to Json format string.

Output : 

         {"srNo":1,"name":"Java","list":["Json","Gson"]}


fromJson() Example 

You can convert your JSON string to Java Object using this function. There is some rules to convert your Json String to Java Object.
  1. Properties in Java Object will match with the Key or properties name in Json String.
  2. If Json string contain property that is not present in Java bean class than its value will not be reflected in Java Bean. 

package com.java.gson;

import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;

public class JsonExample
{
       public static void main(String[] args)
       {
             String str = "{\"srNo\":1,\"name\":\"Java\",\"list\":[\"Json\",\"Gson\"]}";
             try
             {
                    Gson json = new Gson();
                    MyBeanClass bean = json.fromJson(str, MyBeanClass.class);

                    System.out.println(bean);
             }
             catch(Exception ex)
             {
                    ex.printStackTrace();
             }
       }
}

You may used .fromJson() function with FileReader or BufferedReader or InputStreamReader 
to directly read from network or from file where you have save Json string.


Reference
  1. Google Gson -  https://github.com/google/gson
  2. Gson User Guide - https://sites.google.com/site/gson/gson-user-guide#TOC-Goals-for-Gson
  3. Json Wiki - https://en.wikipedia.org/wiki/JSON
  4. Json Official Website - http://json.org/