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

No comments:

Post a Comment