Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Convert json to java object using Gson library

I published the last post about how to convert java object into the json format. We are going to reuse some of its code so take a look at the previous post by clicking here

Make sure you have the Gson library installed in your class path, I described that in my previous post.
Lets create a json file with some sample data in it.

testFile.json

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


Now, lets create a java class which will read the json file and convert that into the java object.

Json2Java.java

package com.amzi.java;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class Json2Java {
    public static void main(String[] args) {

        Gson gson = new Gson();
        try {
            //read json file from the buffered reader object
            BufferedReader br = new BufferedReader(new FileReader(
                    "c:\\users\\amzi\\desktop\\testFile.json"));

            // convert the json string back to object
            TestObject obj = gson.fromJson(br, TestObject.class);

            System.out.println(obj);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

TestObject [ID = 1, name = Amzi, skills = [Java, JSP, JDBC]]

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

Convert Json to Java object using Jackson library

I published a post on "how to convert java object into the json format. In case you missed it, click here for your reference. Today, we are going to reverse that, meaning from the json file we are going to read and convert that into the java object.

We have the json file in the local machine user.json

user.json

{"messages":["Your name is - Amzi","Your Id is - 1","Welcome to the world!!!"],"name":"Amzi","id":1}


I'd assume that you already have the required jackson library in your project class path. I described that in my previous post in detail.

Now, lets create the java file which will read json file and create the java object out of it. For that we are going to use the readValue() method which is available in ObjectMapper class. ObjectMapper class is the part of the jackson library.

Json2Java.java

package com.amzi.java;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Json2Java {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        try {
            // read from file, convert it to user class
            User user = mapper.readValue(new File(
                    "c:\\Users\\Amzi\\Desktop\\user.json"), User.class);

            // display to console
            System.out.println(user);

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

User [id=1, name=Amzi, messages=[Your name is - Amzi, Your Id is - 1, Welcome to the world!!!]]

Convert java object to Json using jackson library

In this example we are going to learn how to convert java object into the json format.

Lets create a maven project into the eclipse workspace. Open up the pom.xml file and paste the following code inside the project node.

If you are not using maven then you may download the library from the google and add it to the class path.

pom.xml

  <repositories>
    <repository>
        <id>codehaus</id>
        <url>http://repository.codehaus.org/org/codehaus</url>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
  </dependencies>


Lets create the User object first. This is a java object with 2 fields and a list.

User.java

package com.amzi.java;

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

public class User {

    private int id = 01;
    private String name = "Amzi";
    private List<String> messages = new ArrayList<String>();
    {

        messages.add("Your name is - " + name);
        messages.add("Your Id is - " + id);
        messages.add("Welcome to the world!!!");

    }

    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> getMessages() {
        return messages;
    }

    public void setMessages(List<String> messages) {
        this.messages = messages;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", " + "messages="
                + messages + "]";
    }
}


Jackson library provides us the writeValue() method and which is available in ObjectMapper class. In this method we are going to pass the location where we want to save the json file.

Java2Json.java

package com.amzi.java;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Java2Json {
    public static void main(String[] args) {

        User user = new User();
        ObjectMapper mapper = new ObjectMapper();

        try {
            // converts user object to json string, and save to a file
            mapper.writeValue(
                    new File("c:\\Users\\Amzi\\Desktop\\user.json"), user);

            // display to console
            System.out.println(mapper.defaultPrettyPrintingWriter()
                    .writeValueAsString(user));
           
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Now, we are done parsing the java object into the json format. Once we run the above java class, we are going to get following output into the console and also the same output will be saved inside the user.json file.

Output:

{
  "messages" : [ "Your name is - Amzi", "Your Id is - 1", "Welcome to the world!!!" ],
  "name" : "Amzi",
  "id" : 1
}