17-Jun-12 (Created: 17-Jun-12) | More in 'Android Public'

World of JSON & GSON

In the world of dynamic HTML, we always need a fat free version of data exchange between the server and the client.As the web world becomes more dynamic, the use of Javascript have considerably increased. With frameworks like Jquery, DOJO etc, use of javascript have become very easy and less cumbersome. These JS frameworks can create dynamic HTML based on data from the server. Another biggest change on the web world is the use of AJAX. The more interactive the web is, AJAX will be used to a greater extent so that the user gets a seamless feeling. For all the above scenarios, what we need is a data format which is easy and efficient. Here we will discuss about JSON - the fat free data format which is used across the board in web, mobile and even client applications.

What is JSON?

JSON stands for JavaScript Object Notation. (JSON is pronounced like the name Jason)

It is a data format. The JSON data format is ideally suited for consumption by a JavaScript program.

Why JSON?

  1. Its platform independent
  2. Its programming language independent
  3. Easy for humans to read and interpret
  4. It is text format.
  5. Its lightweight data-interchange format.
  6. Ajax calls can use JSON to enable cross-domain calls.

What is the Structure of JSON?

JSON is built on two structures:

  1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

  1. An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
  2. An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
  3. A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
  4. A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string.

JSON Object

Example for JSON Object

Below is the consumer representation in JSON. Look at it, its so simple and easily understandable.

{

   “consumer”: {

      “name”:”Deepak”

     “age”: 30

     “email” : “[email protected]

   }

}

JSON Values

The types represented in JSON are strings, numbers, booleans, object, arrays, and null.

JSON Arrays

Example

Here is the consumer array.

{

  [“name”:”Deepak”,”age”:30,”email”:”[email protected]”],

  [“name”:”Dhanu”,”age”:29,”email”:”[email protected]”],

  [“name”:”Ajay”,”age”:30,”email”:”[email protected]”],

}

What is GSON?

I loved using JSON for transport on my projects. But when i have a complex structure i felt the use of Normal JSON parsers on the server side felt little cumbersome and time taking. I really wanted a way where i feed the JSON structure to a method and get a custom well defined object as a result of it. This thought made  me research on such programs and i finally landed GSON. My life became so much more easier with it.

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at http://code.google.com/p/google-gson.

Why GSON?

  1. Provide easy to use mechanisms like toString() and constructor (factory method) to convert Java to JSON and vice-versa
  2. Allow pre-existing unmodifiable objects to be converted to and from JSON
  3. Allow custom representations for objects
  4. Support arbitrarily complex object
  5. Generate compact and readability JSON output

Dealing with a class of Primitive type Members

Lets say i have a consumer object with below structure in my project.

public class Consumer

{

                        private String name;

                        private int age;

                       private String email;

                public String getName() {

                        return name;

                }

                public void setName(String name) {

                        this.name = name;

                }

                public int getAge() {

                        return age;

                }

                public void setAge(int age) {

                        this.age = age;

                }

                public String getEmail() {

                        return email;

                }

                public void setEmail(String email) {

                        this.email = email;

                }

}

Serialization Example

i can use the below code to convert the Consumer object to a JSON equivalent.

Consumer consumer = new Consumer();

consumer.setName(“Deepak”);

consumer.setAge(30);

consumer.setEmail(“[email protected]”);

Gson gson = new Gson();

String json =  gson.toJson(consumer);

The above code output will look like

{“name”:”Deepak”,”age”:30,”email”:”[email protected]”}

Deserialization Example

Here i will show a simple deserialization sample. The gson.fromJson() takes two parameters:

  1. JSON to be deserialized
  2. Class type

String jsonStr = {“name”:”Deepak”,”age”:30,”email”:”[email protected]”};

Gson gson = new Gson();

Consumer consumer = gson.fromJson(jsonStr, Consumer.class);

Dealing with Typed Collections

Serialization Example

Lets take the same Consumer class as an example. Say that we have a list of consumers and we need to GSON to serialize and deserialize to and from JSON format.

/** Created a consumers list **/

List<Consumer> consumers = new ArrayList<Consumer>();

/**Adding 3 consumer to the list**/

consumers.add(new Consumer(“Deepak”,30,”[email protected]”));

consumers.add(new Consumer(“Dhanu”,29,”[email protected]”));

consumers.add(new Consumer(“Ajay”,30,”[email protected]”));

Gson gson = new Gson();

String jsonStr = gson.toJson(consumers);

This will create a JSON object as below:

{

  [“name”:”Deepak”,”age”:30,”email”:”[email protected]”],

  [“name”:”Dhanu”,”age”:29,”email”:”[email protected]”],

  [“name”:”Ajay”,”age”:30,”email”:”[email protected]”],

}

Deserialization Example

When we have typed collections we will need to create a type token and tell GSON that its dealing with this type.

String json = “{

  [\“name\”:\”Deepak\”,\”age\”:30,\”email\”:\”[email protected]\”],

  [\“name\”:\”Dhanu\”,\”age\”:29,\”email\”:\”[email protected]\”],

  [\“name\”:\”Ajay\”,\”age\”:30,\”email\”:\”[email protected]\”],

}”;

Gson gson = new Gson()

Type newType = new TypeToken<ArrayList<Consumer>>(){}.getType();

                        

List<Consumer> models = gson.fromJson(json,newType);

This will create a list of consumer objects with the values as in the JSON string.

What Libraries you need to Include?

Google-gson.jar http://code.google.com/p/google-gson/downloads/list