Convert java object to json format using Gson library

In one of my previous post we have discussed about the same topic but using jackson library. For your reference - click here

In this example we are going to see how to convert java object into the json format using Google's Gson library.

Gson is pretty easy to understand and it has mainly below two methods to note.
  • toJson() – Convert Java object to JSON format
  • fromJson() – Convert JSON into Java object
First of all, in order for us to compile the code we need the Gson library. For maven users please paste the below dependency inside your pom.xml file. Non maven users can download it online and paste it in the project class path.

pom.xml

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

Now, lets create a java test object with some initialized values. Later on we are going to convert this java object to json format using Gson library.

TestObject.java

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

public class TestObject {
    private int id = 1;     private String name = "Amzi";     private List<String> skills = new ArrayList<String>() {         {             add("Java");             add("JSP");             add("JDBC");         }     };     public int getId() {         return id;     }     public void setId(int id) {         this.id = id;     }     public String getName() {         return name;<     }     public void setName(String name) {         this.name = name;     }     public List<String> getSkills() {         return skills;     }     public void setSkills(List<String> skills) {         this.skills = skills;     }     @Override     public String toString() {         return "TestObject [ID = " + id + ", name = " + name + ", skills = "                 + skills + "]";     } }


Below is the core logic which will enable us to convert the java object to json. We are going to use the toJson() method which is available in Gson object

Java2Json.java

package com.amzi.java;
import java.io.FileWriter; import java.io.IOException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Java2Json {     public static void main(String[] args) {         TestObject obj = new TestObject();         //initialize Gson object         //setPrettyPrinting().create() is for batter formating.         Gson gson = new GsonBuilder().setPrettyPrinting().create();         // convert java object to JSON format,         // and returned as JSON formatted string         String json = gson.toJson(obj);         try {             // write converted json data to a file named "testFile.json"             FileWriter writer = new FileWriter(                     "c:\\users\\amzi\\desktop\\testFile.json");             writer.write(json);             writer.close();         } catch (IOException e) {             e.printStackTrace();         }         System.out.println(json);     } }


Along with the below output into the console we may also check for the newly created testFile.json in the location we mentioned.

Output:

{
  "id": 1,
  "name": "Amzi",
  "skills": [
    "Java",
    "JSP",
    "JDBC"
  ]
}

6 comments:

  1. Very attractive and informative blog about Java... keep rocks..

    Java Training in Chennai

    ReplyDelete
  2. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.

    rpa training in chennai
    rpa training in bangalore
    rpa training in pune
    rpa training in marathahalli
    rpa training in btm

    ReplyDelete
  3. It’s really great information for becoming a better Blogger. Keep sharing, Thanks...

    Learn Hadoop Training from the Industry Experts we bridge the gap between the need of the industry. Softgen Infotech provide the Best Hadoop Training in Bangalore with 100% Placement Assistance. Book a Free Demo Today.
    Big Data Analytics Training in Bangalore
    Tableau Training in Bangalore
    Data Science Training in Bangalore
    Workday Training in Bangalore

    ReplyDelete