Android Series: Parsing JSON data with GSON

Android Series: Parsing JSON data with GSON

Today I will describe how to parse json data using Gson open source library and how to convert it at the same time to java objects.
This is a typical cookbook example and should be very easy to follow.


1. Create an Android application with one activity, name it as you wish, if you are doing it in eclipse all the basic stuff will be generated for you which is exactly what we need.
2. Find an example url which responds in JSON, I have used Twitter Trends found here: http://search.twitter.com/trends.json
The example response looks like this:

{"as_of":"Thu, 25 Feb 2010 11:30:17 +0000","trends":[{"name":"#nowplaying","url":"http://search.twitter.com/search?q=%23nowplaying"},{"name":"#nothingworsethan","url":"http://search.twitter.com/search?q=%23nothingworsethan"},{"name":"Dubai Mall","url":"http://search.twitter.com/search?q=%22Dubai+Mall%22"},{"name":"iPad Gets","url":"http://search.twitter.com/search?q=%22iPad+Gets%22"},{"name":"#SuperJuniorTrot","url":"http://search.twitter.com/search?q=%23SuperJuniorTrot"},{"name":"Justin Bieber","url":"http://search.twitter.com/search?q=%22Justin+Bieber%22"},{"name":"Click","url":"http://search.twitter.com/search?q=Click"},{"name":"Jaebum","url":"http://search.twitter.com/search?q=Jaebum"},{"name":"#tosavemoney","url":"http://search.twitter.com/search?q=%23tosavemoney"},{"name":"Protection","url":"http://search.twitter.com/search?q=Protection"}]}



As you can see this json data contains date attribute called ‘as_of’ as well as array of items, each consisting of name and url attributes.
We will create two simple java classes wich will hold that information.
First one is TwitterTrends.java

package com.softwarepassion.jsonexample;

import java.util.Date;
import java.util.List;

public class TwitterTrends {

    private String as_of;
    private List<TwitterTrend> trends;
   
    public String getAs_of() {
        return as_of;
    }
    public void setAs_of(String asOf) {
        as_of = asOf;
    }
    public List<TwitterTrend> getTrends() {
        return trends;
    }
    public void setTrends(List<TwitterTrend> trends) {
        this.trends = trends;
    }
   
   
   
}

And the second one is a simple TwitterTrend.java

package com.softwarepassion.jsonexample;

public class TwitterTrend {
    private String name;
    private String url;
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}

TwitterTrends contains a list of TwitterTrend objects, both of them are simple beans and are very similar to the json response if you look closely :).

Now the fun part begins.

Download the Gson library from http://code.google.com/p/google-gson/ and add it to your java build path in eclipse.
Once you do that, you can now transform your json response to Java object on Android Platform:
Get the response as InputStream:

public InputStream getJSONData(String url){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI uri;
        InputStream data = null;
        try {
            uri = new URI(url);
            HttpGet method = new HttpGet(uri);
            HttpResponse response = httpClient.execute(method);
            data = response.getEntity().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
       
        return data;
    }

Then use that input stream to create your java objects:

public void runJSONParser(){
        try{
        Log.i("MY INFO", "Json Parser started..");
        Gson gson = new Gson();
        Reader r = new InputStreamReader(getJSONData("http://search.twitter.com/trends.json"));
        Log.i("MY INFO", r.toString());
        TwitterTrends objs = gson.fromJson(r, TwitterTrends.class);
        Log.i("MY INFO", ""+objs.getTrends().size());
        for(TwitterTrend tr : objs.getTrends()){
            Log.i("TRENDS", tr.getName() + " - " + tr.getUrl());
        }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

Easy ha!

19 responses on “Android Series: Parsing JSON data with GSON

  1. fromUkraine March 30, 2010 at 7:00 pm

    Thnx a lot! quite short but very helpfull article!

  2. Schwaib April 20, 2010 at 5:04 pm

    Really nice article.. i just tried it, it works fine.. but i have a question. I am converting aa array of json objects to JavaObjs its length is around 90 and i found it taking more than 1 minute for this activity. Is it fine or GSON is not optimized for android???

  3. admin April 21, 2010 at 12:32 pm

    Strange, 90 is not such a big number, I would rather guess its the network speed or you have really large object to parse. I cannot say GSON is optimized for android, as I guess its not optimized for any platform, but its pretty small and I haven’t seen any complaints about its speed. You would have to look for answers on the gson project website.

  4. Schwaib April 21, 2010 at 3:49 pm

    thnx for your reply, it really help me to wipe-out some grey areas.

    I was also wondering 90 is not a big number where each object only contain 4-5 properties in it. As far as internet speed is concerned i don’t think its network speed issue,
    This is the line that takes around 40-45 secs for 90 objects to convert, where ‘json’ is the object returned from service service call.
    MyDTOLite[] ass = gson.fromJson(json.optString(“GetMyDTOLiteResult”), MyDTOLite[].class);

    I’ll raise this question at GSON project site as well.

  5. Pop May 15, 2010 at 8:57 am

    Hi,

    JSON has built in get and opt commands for parsing JSON objects and identify components. Is there any advantage in using GSON which is an external library for this purpose?

  6. towhid June 20, 2010 at 10:20 am

    Awesome ….man…….you r the One……..

  7. shrek July 14, 2010 at 11:20 pm

    hi!!thanks for the article..great one ..help me understand a lot..
    i m new to android and json ..so im somehow unable to run the code

    may be i m doing some mistake..will it be possible to send me working android project fr the above code..pls it would b really great if u cn help

    thanks in advance!

  8. Jobe August 3, 2010 at 12:00 am

    How would you pull these results into a ListView?

  9. admin August 3, 2010 at 7:06 am

    Check out my other tutorial on how to use ListView 🙂

  10. Matt December 29, 2010 at 6:14 am

    Thanks, man.

    I’ve been looking for a nice clear example for hours. This got me up and running quick!

    Thanks, again!

  11. tamilmaran March 17, 2011 at 8:25 am

    hi i got response this like

    {“serviceType”:”IMAGE_ANDROID”,”parameters”:
    [[{“itemId”:”it003376″,”itemNameInEng”:”8th Chennai International Film Festival Photos”,”itemSmallImage”:”http://122.183.217.134:8080/sivajitv/photos/20101216001017.jpg”,”count”:”110″},{“itemId”:”it003375″,”itemNameInEng”:”Actress Aishwarya Rai Special Photos”,”itemSmallImage”:”http://122.183.217.134:8080/sivajitv/photos/20101215230917.jpg”,”count”:”7″}]]}

    how can i parse the value

    please help me

    i used your coding but it does not work for this response

  12. admin March 17, 2011 at 9:22 am

    ‘it doesn’t work’ its not enough to help you

  13. Peter March 30, 2011 at 11:06 am

    Hi, i can’t parse . I followed your tutorial, except in one thing : i put the getJsonData in another class, and i put in in static.
    When i look for the in the debugger :
    the problem is at java.io.Reader
    at java.io.StreamReader

  14. Jose Vigil May 9, 2011 at 6:11 am

    Hi,

    Nice article.

    Twitter trend link has changed to http://api.twitter.com/1/trends.json

    Regards,
    Jose

  15. Nick May 31, 2011 at 4:56 pm

    Is there any advantage to using GSON as opposed to android’s built-in JSON library?

  16. Marco da Gualdo August 8, 2011 at 9:35 pm

    Excellent tutorial, thank you so much 🙂

  17. fikra December 2, 2012 at 8:10 pm

    what are the use of TwtterTrend & TwitterTrends classes?
    I am really new for this world, sorry for very basic question.

Leave a Reply