Parsing JSON using GSON in Android

As part of the college mini project,  I along with my group, developed a micro-blogging platform for Android. One of the biggest hurdles I had to face was of choosing the proper data format for receiving responses from the web service. I needed something that was fast as well as easy to understand and parse.  I first chose XML as it was easy to read and mostly because I knew no other alternatives. But parsing XML certainly wasn’t easy. With the variety of tags in the responses from the server and the heaviness of XML format, it just became impossible to use it.

That’s when JSON(JavaScript Object Notation) came up as an alternative to XML. I was circumspect about using JSON at first as I had doubts about its readability and ease of deserialization. But those doubts were not much more than just superstitions. JSON is smaller and easier to parse, than it’s XML equivalent. Many say its less readable than XML, but considering it was used for data interchange, readability was not important.

The easiest way to parse JSON and convert to POJO (Plain Old Java Objects) in Android is to use the Google’s GSON library.

Download GSON

Download the latest GSON library from

Google GSON

Add this library into your Android Project as an external by right clicking on the desired project and

Properties -> Java Build Path -> Libraries -> Add External JARs and point to the downloaded gson library.

Format of JSON response.

Suppose, the JSON response recieved from the webservice is of the following format.

{ "posts":
  [      
     { "post": 
        {
       "username": "John",  
       "message": "I'm back",
       "time": "2010-5-6 7:00:34"
            }},
        {    "post":
            {
                "username": "Smith",
                "message": "I've been waiting",
                "time": "2010-4-6 10:30:26"
            }}]}


It is an array of JSON Objects.  You have to develop a class structure in accordance with the structure of the JSON response received.  For the above example I had the class structure based on the following logic.

The “posts” data structure contain multiple posts, each of which contains an “post” type. In order to match this structure, I need to have 3 classes namely PostList, PostContainer and Posts. The PostList class should have an ArrayList of objects of type PostContainer. PostContainer needs just one field which is an object of type Posts. Posts classes must have  3 fields namely username, message and time.

public class PostList {

private List<PostContainer> posts = new ArrayList<PostContainer>();
public List<PostContainer> getPostContainterList() {
return posts;
}
}

class PostContainer{
Posts post;
public Posts getPost(){
return post;
}
}

public class Posts {
String message;
String time;
String username;
}

Deserialization Part

Now let’s get into the real business of Deserialization. Using GSON this can be done very easily.

First, import the Google gson library into the class in which JSON String is to be deserialized

import com.google.gson.Gson;

I am initializing an ArrayList which contains objects of type Posts

private List<Posts> mObjectList =  new ArrayList<Posts>() ;

This can be latter on used for adding the Posts objects after deserialization is done.

String jsonString = “Insert your JSON Data here”

Instantiate an Object of type PostList

PostList list = null;

list = getPostList(jsonString);

The following function deserializes JSON response to an Object of type PostList and returns it.

protected PostList getPostList (String jsonString){
PostList pl = null;
Gson gson = new GSON;
pl = gson.fromJson(jsonString, PostList.class);
return pl;
}

What the function getPostList does is, it creates an object of type GSON and deserialize the JSON String to POJO using that object(gson).

gson.fromJson(jsonString, PostList.class)

The first parameter to the function is the JSON String and second parameter is the name of the class to which it should be deserialized. Two important things have to be taken care of while using GSON to parse JSON

  • Tags in JSON String and name of fields of the respective classes should match exactly.
  • Object hierarchy should be built correctly.

Failure to comply to the both conditions above would result in some or all of the fields of the classes being left null.

Having parsed the JSON string to POJO, we can get various Posts objects separately and add it to the ArrayList which we created earlier as follows.

List <PostContainer> post_list = list.getPostContainterList();
PostContainer pc;
for (int i = 0; i < post_list.size(); i++) {
pc = post_list.get(i);
mObjectList.add(pc.getPost()); //Adding each post to the list

This ArrayList can be used to populate a custom list view. If you have any doubts regarding this post, feel free to ask through comments. In the next post, I will post an tutorial on how to build a custom listview which looks the twitter timeline efficiently.

About these ads

4 Comments

Filed under Android

4 responses to “Parsing JSON using GSON in Android

  1. Thank you. That helped me alot :)

  2. Ravishankar V

    Hi Nice approach. I think you can simplify much further by using a inner static class as given in this link.

    http://stackoverflow.com/questions/4266544/json-deserialization-using-gson

    http://sites.google.com/site/gson/gson-user-guide#TOC-Nested-Classes-including-Inner-Clas

    and the documentation

  3. Nayanesh Gupte

    what is wrong with this. I’m facing the same problem.
    EXCEPTION :java.lang.RuntimeException: Unable to invoke no-args constructor for class com.xyz. Register an InstanceCreator with Gson for this type may fix this problem.

    eg:

    jstring =[
    {“name”:”Dell”,
    “id”:”1″,
    “categories”:[“Consumer Electronics”],
    “number_of_alerts”:”1″,
    “logo_url”:”http:\/\/192.168.1.17\/yooz\/web\/uploads\/dell_logo.png”
    },
    {“name”:”Baskin Robbins”,
    “id”:”2″,
    “categories”:[“Food”],
    “number_of_alerts”:”0″,
    “logo_url”:”http:\/\/192.168.1.17\/yooz\/web\/uploads\/br.png”
    },
    {“name”:”Monginis”,
    “id”:”3″,
    “categories”:[“Food”],
    “number_of_alerts”:”3″,
    “logo_url”:”http:\/\/192.168.1.17\/yooz\/web\/uploads\/Monginis_logo.png”
    },
    {“name”:”Levis”,
    “id”:”4″,
    “categories”:[“Fashion Accessory”],
    “number_of_alerts”:”0″,
    “logo_url”:”http:\/\/192.168.1.17\/yooz\/web\/uploads\/levis.png”
    },
    {“name”:”Lacoste”,
    “id”:”5″,
    “categories”:[“Clothing”],
    “number_of_alerts”:”0″,
    “logo_url”:”http:\/\/192.168.1.17\/yooz\/web\/uploads\/lacoste_logo.jpg”
    },
    {“has_next”:1}
    ]

    public static boolean ParseJSONBrand(String jString) {

    try {

    Gson gson = new Gson();
    Brand brand[] = gson.fromJson(jString, Brand[].class);

    for (int i = 0; i < brand.length-1; i++) {
    Log.d("JSON PARSER", " jstring :" + jString + "obj :"
    + brand.length);

    brand[i]= new Brand();
    Log.d("JSON PARSER", "NAME :" + brand[i].brandName);
    Log.d("JSON PARSER", "ID :" + brand[i].brandId);
    Log.d("JSON PARSER", "ALERTS :" + brand[i].no_of_alerts);
    Log.d("JSON PARSER", "THUMBNAIL :" + brand[i].thubmnail);

    for (int j = 0; j < brand[i].category.length; j++) {
    Log.d("JSON PARSER", "category["+j+"] :" + brand[i].category[j]
    + "\n\n");

    }

    }
    return true;

    } catch (Exception e) {
    // TODO: handle exception
    Log.d("ParseJSONBrand ", "EXCEPTION :" + e.toString());
    // e.printStackTrace();

    }

    return false;
    }

    public class Brand {

    public String brandName;
    public String brandId;
    public String thubmnail;
    public String[] category;
    public String no_of_alerts;

    public Brand() {
    // TODO Auto-generated constructor stub
    this.brandName= new String();
    this.brandId=new String();;
    this.no_of_alerts=new String();;
    this.thubmnail=new String();
    this.category[3] = new String();

    }
    }

  4. “JSON is smaller and easier to parse, than it’s XML equivalent. Many say its less readable than XML, but considering it was used for data interchange, readability was not important.”

    Yes. That is correct. Even I have used in my REST programming, it is very easy to use JSON with the javascript code too. I came across this link for converting the JSON to java objects, which is very useful.

    http://www.javabeat.net/2012/04/parsing-json-using-java-and-gson-library/

    Which version of Android you are using?. Is there any separate version of GSON to be used fro the Android? Please clarify me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s