experiences & encouters from behind the android development furnace

Using GSON to parse JSON on Android


Although mobile devices have on a hardware level become akin to what hardcore gaming machines were within the last decade their core strength has to be the ability to connect to resources over the Network.  I guess what the previous sentence tries to convey is the fact that although more and more processing can happen client-side without a doubt this is only a supplement to the ability to leverage “off-site” resources like web services etc.

Generally the trend for major players who offer  Application Programmer Interface’s (API) is to supply their data either in Extensible Markup Language (XML) or in Javascript Object Notation (JSON).  In general JSON wins over XML on mobile perhaps more for the reason that it is lighter (less tags and other semantic baggage) than for any other reason.  On the other hand XML does lend itself more towards context aware data in terms of the ability to deduce information from it’s eXtensibility.

Both formats can easily be processed on Android by means of opensource libraries, however because I find that in general JSON wins for the transfer format 90% of the time I figured to write a post on the ease of use in terms of using what I rate the best JSON library for Android google-GSON.

Obviously the first thing one needs to be able to retrieve some JSON from a service would be the API endpoint.  Usually these come with significant security in the form of token passing etc, however for the purpose of this example it accepts only an HTTP GET and returns a JSON representation of the Southern African countries and each of their capital cities.

You can find the call at or if you want to do something similar the script looks like this:

 $countryCapitalsJson =
 {"country":"Angola", "capital": "Luanda"},
 {"country":"Botswana", "capital": "Gaborone"},
 {"country":"Democratic Republic of the Congo", "capital": "Kinshasa"},
 {"country":"Lesotho", "capital": "Maseru"},
 {"country":"Madagascar", "capital": "Antananarivo"},
 {"country":"Malawi", "capital": "Lilongwe"},
 {"country":"Mauritius", "capital": "Port Louis"},
 {"country":"Mozambique", "capital": "Maputo"},
 {"country":"Namibia", "capital": "Windhoek"},
 {"country":"South Africa", "capital": "Pretoria"},
 {"country":"Swaziland", "capital": "Lobamba"},
 {"country":"Tanzania", "capital": "Dodoma"},
 {"country":"Zambia", "capital": "Lusaka"},
 {"country":"Zimbabwe", "capital": "Harare"}

 header('Content-type: application/json');
 echo $countryCapitalsJson;

As you can see from the JSON that is returned it is essentially an array of Country name & Capital City pairs. In order for the JSON library to magically transform this JSON represented dataset into POJO (Plain Old Java Object) models you need to create the classes which are to be used to represent these domain objects.

In the case of the example I created a Response object which needs to contain a member variable for the data field as it is the next element in the JSON document’s data structure.  Note that the data member variable in our Response class is an arraylist of type Country which facilitates simple parcelability but more about that in a later post.

package com.androidsmith.sacc;

import java.util.ArrayList;

import com.androidsmith.sacc.model.Country;

public class Response {

 ArrayList<Country> data;

 public Response() {
 data = new ArrayList<Country>();


Next of course the Country model object:

package com.androidsmith.sacc.model;

public class Country {

 String country;
 String capital;

 public Country() { = ""; = "";

 public String getCountry() {

 public String getCapital() {

After you have your model layer setup to represent the nested domain objects represented in JSON it is merely a matter of utilizing the magic of the GSON library.  In essence all you need to do is call the relevant method on an instance of the Gson class and pass it a reference to the reader containing your JSON response’s InputStream as well as the Class of your root level entity (in our case Response.class):

Gson gson = new Gson();
 this.response = gson.fromJson(inputStreamReader, Response.class);

In the case of an exception not having been raised this.response should now contain your model hierarchy as represented in the JSON retrieved ready for you to do whatever you want to with.

Please feel free to download the sample project for the complete eclipse project.

Libraries do bring magic to your sourcecode and while it works it is great, however when a library starts behaving strangely it can become VERY frustrating.  However in our lives we do not always have time to or want to re-invent the wheel.  Luckily this magical library is opensource and therefore offers a very helpful and debuggable option as a JSON parsing library.

“Any sufficiently advanced technology is indistinguishable from magic”
Arthur C. Clarke, “Profiles of The Future”, 1961 (Clarke’s third law)
English physicist & science fiction author (1917 – )

Leave a Reply

Required fields are marked *.