Wednesday, 4 July 2012

How to convert Java object to / from JSON (Gson)


JSON is stand for JavaScript Object Notation, it is a lightweight data-interchange format. You can see many Java applications started to throw away XML format and start using json as a new s data-interchange format. Java is all about object, often times, you need to convert an object into json format for data-interchange or vice verse.

In this article, we show you how to use Gson, JSON library, to convert object to/from json.

Gson is easy to learn and implement, what we need to know are following two methods

    toJson() – Convert Java object to JSON format
    fromJson() – Convert JSON into Java object

1. Gson Dependency

For non-Maven user, get the Gson library from Gson official site, for Maven user, declares following dependency in your pom.xml.

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

A pojo, with initialized values. Later use Gson to convert this object to/from JSON formatted string.

package com.mkyong.core;

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

public class DataObject {

    private int data1 = 100;
    private String data2 = "hello";
    private List<String> list = new ArrayList<String>() {
      {
        add("String 1");
        add("String 2");
        add("String 3");
      }
    };

    //getter and setter methods

    @Override
    public String toString() {
       return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
        + list + "]";
    }

}
3. toJson() example

Convert object to JSON string, and save it as “file.json“.

package com.mkyong.core;

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;

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

    DataObject obj = new DataObject();
    Gson gson = new Gson();

    // 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 "file.json"
        FileWriter writer = new FileWriter("c:\\file.json");
        writer.write(json);
        writer.close();

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

    System.out.println(json);

    }
}

Output

{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}

4. fromJson() example

Read data from “file.json“, convert back to object and display it.

package com.mkyong.core;

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

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

    Gson gson = new Gson();

    try {

        BufferedReader br = new BufferedReader(
            new FileReader("c:\\file.json"));

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

        System.out.println(obj);

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

    }
}

Output

DataObject [data1=100, data2=hello, list=[String 1, String 2, String 3]]

No comments:

Post a Comment