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

In this artice, you will learn about the newly JSON library named Gson.

Gson is a Java library that can be used to convert Java Objects into its JSON representation

Gson is easy to learn and implement, what we need to know is the following two methods
1. toJson() – convert java object to JSON format
2. fromJson() – convert JSON into java object

1. toJson() example

import com.google.gson.Gson;
 
class TestObjectToJson {
  private int data1 = 100;
  private String data2 = "hello";
}
 
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
String json = gson.toJson(obj);

Output

Return String in json format {“data1″:100,”data2″:”hello”}

2. fromJson() example

import com.google.gson.Gson;
 
class TestJsonFromObject {
  private int data1;
  private String data2;
}
 
String json = "{'data1':100,'data2':'hello'}";
Gson gson = new Gson();
TestJsonFromObject obj = gson.toJson(json, TestJsonFromObject.class);

Output

Return an object (TestJsonFromObject) contains data1 (100) and data2 (hello).

Reference

Json Official site – http://www.json.org/
Json in Wiki – http://en.wikipedia.org/wiki/JSON
Google Gson – http://code.google.com/p/google-gson/