Tuesday, December 3

Convert Java to JSON and JSON to Java using GSON

Introduction:  JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format. Sometimes we need to convert a java object into JSON format for data-interchange or JSON to java object. We can convert Java to JSON or JSON to Java by using GSON library provided by Google. GSON is an open source Java library used to serialize and de-serialize java object to JSON.The jar file can be downloaded from the following URL:
After downloading, add this jar file to your project path. 

This library has two important methods:

toJson() : this method converts Java object to JSON.
fromJson() : this method converts JSON to Java.

Convert Java to JSON using GSON
In this demo, I created there classes.
Customer.java : Holds customer information  such as Id, First Name, Last Name and products.
JavaToJson.java: It instantiates a customer object. It creates a GSON object and pass this customer object by calling “toJson()” method.

Convert JSON to JAVA using GSON
JsonToJava.Java:  It reads a file that has data in JSON format and then it converts JSON into java object. It calls “fromJson()” method and pass the buffer from JSON file.

Code:
package javaJsonExample;


  import java.util.List;
 
  public class customer {
           
            private String FirstName;
            private String LastName;
            private String Id;
            private List<String> products;
           
            public customer(){}
           
            public String getFirstName() {
                        return FirstName;
            }
           
            public String getLasttName() {
                        return LastName;
            }
            public String getId() {
                        return Id;
            }

            public void setFirstName(String fname)
            {
                        FirstName=fname;
            }
   public void setLastName(String lname)
            {
                        LastName=lname;
            }
           
            public void setId(String id)
            {
                        Id=id;
            }
            public List<String> getProducts()
            {
                        return  products;
            }
           
            public void setProducts(List<String> prod) {
                        this.products=prod;
            }
}


package javaJsonExample;
import com.google.gson.Gson;
import java.util.ArrayList;


public class javaToJson {
           
           
            public static void main(String args[])
            {
                        //create a customer object
                        customer cust=new customer();
                       
                        //set attributes
                        cust.setFirstName("Kathy");
                        cust.setLastName("Smith");
                        cust.setId("c101");
                       
                        //store products customer bought
                        ArrayList<String> prod=new ArrayList<String> ();
                         prod.add("Iphone");
                         prod.add("Camera");
                         prod.add("TV");
                         
                         cust.setProducts(prod);
                         //create GSON Object
                         Gson obj=new Gson();
                         //call toJson() method and pass the customer object
                         System.out.println(obj.toJson(cust));
                         
                       
            } 
            }


Output:
{"FirstName":"Kathy","LastName":"Smith","Id":"c101","products":["Iphone","Camera","TV"]}
I saved this outout as cust.json in my machine and I’ll use this Json file to convert it to Java.

package javaJsonExample;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class jsonToJava {
           
            public static void main(String args[])
            {
                       
                        try {
                       
                       
                        File file=new File("c:\\project\\cust.json");
                        //Read the file in bufferReader
                         BufferedReader buff = new BufferedReader(new FileReader(file));
                        //Create GSON Object
                        Gson obj=new Gson();
                        //call fromJson() method and pass bufferRedaer and reference of customer object
                        customer cust=obj.fromJson(buff, customer.class);
                        //print customer object
                        System.out.println ("customer Id:" + cust.getId());
                        System.out.println ("customer First Name:" + cust.getFirstName());
                        System.out.println ("customer Last Name:" + cust.getLasttName());
                        System.out.println("Products Bought:");
                        for (int i=0; i < cust.getProducts().size() ;i++)
                        {
                        System.out.println ( cust.getProducts().get(i));
                        }
                       
                        }catch(FileNotFoundException e)//catch file not found exception
                        {
                                    e.printStackTrace();
                        }
            }

}

Output:
customer Id:c101
customer First Name:Kathy
customer Last Name:Smith
Products Bought:
Iphone
Camera
TV



No comments:

Post a Comment