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 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
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
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:
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:
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!
Thnx a lot! quite short but very helpfull article!
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???
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.
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.
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?
Awesome ….man…….you r the One……..
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!
How would you pull these results into a ListView?
Check out my other tutorial on how to use ListView 🙂
Thanks, man.
I’ve been looking for a nice clear example for hours. This got me up and running quick!
Thanks, again!
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
‘it doesn’t work’ its not enough to help you
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
Hi,
Nice article.
Twitter trend link has changed to http://api.twitter.com/1/trends.json
Regards,
Jose
Is there any advantage to using GSON as opposed to android’s built-in JSON library?
Excellent tutorial, thank you so much 🙂
what are the use of TwtterTrend & TwitterTrends classes?
I am really new for this world, sorry for very basic question.