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"
  ]
}

8 comments:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  2. Very attractive and informative blog about Java... keep rocks..

    Java Training in Chennai

    ReplyDelete
  3. 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
  4. Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.

    AWS Online Training |Best Online AWS Certification Course
    AWS Training in Chennai | Advanced Amazon Web Services Training Institute in Chennai
    AWS Training in Bangalore |Best AWS Training Institute in Bangalore

    ReplyDelete
  5. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    Best Devops online Training
    Online DevOps Certification Course - Gangboard

    ReplyDelete