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!