Previously you had learnt to consume a REST Web Service in JSON and parse result to display data in an Android application. To start from basics, I show you raw method that uses only standard SDK and no third-party libraries. I think it’s better when you begin to understand how things work.

Now, you know raw method so we can study methods that make your life easier. To parse JSON in Android and in Java more globally, there are several third party libraries and today, we’re going to learn to use Gson library.

Gson is a Java library to convert JSON to Objects and vice-versa created by Google. Here, we’re going to use Gson only to parse JSON content.

Rather than using a sample JSON format, we can use JSON format from a Web Service known. We’re going to use OpenWeatherMap API to get Current Weather available here : http://api.openweathermap.org/data/2.5/weather?q=London,uk . Output is the following for that call :

{"coord":{"lon":-0.13,"lat":51.51},
 "sys":{"type":3,"id":60992,"message":0.2796,"country":"GB","sunrise":1421049681,"sunset":1421079386},
 "weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],
 "base":"cmc stations",
 "main":{"temp":283.6,"humidity":93,"pressure":1006.9,"temp_min":283.55,"temp_max":283.65},
 "wind":{"speed":8.87,"deg":225.002},
 "rain":{"1h":0.6},
 "clouds":{"all":92},
 "dt":1421094268,
 "id":2643743,
 "name":"London",
 "cod":200}

Gson lets you to convert JSON to Objects. So, we need objects that map OpenWeatherMap format for Current Weather. It’s a long work and we can gain some time by using a tool that uses JSON format from our sample output to generate all the POJOs associated.

Named Jsonschema2Pojo, this tool is freely available on Github. We paste the content of our output sample and we configure the generation by choosing root class, package name and some other options like using long for integers.

jsonschema2pojo
When sources are generated, you can get a Jar with all your POJOs.

POJOs generated are the following :

  • Clouds
  • Coord
  • CurrentWeather (root class)
  • Main
  • Rain
  • Sys
  • Weather
  • Wind

Each POJO represents an object in our JSON sample output.

Now, we can create a simple Java project to try to parse our JSON sample output with Gson and our generated objetcs put in com.ssaurel.gson.model package.

To parse with Gson, it’s really simple because you need only to instantiate a Gson object and then to call its fromJson method with JSON source in first parameter and root class of objects to map in second parameter. Code is like this :


public class GsonSample {

  public static final Calendar c = Calendar.getInstance();
  public static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(
    "HH:mm");

  public static void main(String[] args) {
    String strJson = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"sys\":{\"type\":3,\"id\":60992,\"message\":0.0048,\"country\":\"GB\",\"sunrise\":1421049681,\"sunset\":1421079386},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":283.85,\"humidity\":92,\"pressure\":1007.6,\"temp_min\":283.85,\"temp_max\":283.85},\"wind\":{\"speed\":1,\"gust\":6.6,\"deg\":225},\"rain\":{\"3h\":3},\"clouds\":{\"all\":92},\"dt\":1421090368,\"id\":2643743,\"name\":\"London\",\"cod\":200}";

    Gson gson = new Gson();
    CurrentWeather currentWeather = gson.fromJson(strJson,
      CurrentWeather.class);

    if (currentWeather != null) {
      System.out.println("City : " + currentWeather.getName());
      List<Weather> weathers = currentWeather.getWeather();
      Weather weather = weathers.get(0);
      System.out.println("Condition : " + weather.getDescription());

      Main main = currentWeather.getMain();
      System.out.println("Temperature : "
        + (int) (main.getTemp() - 273.15) + "°C");

      Sys sys = currentWeather.getSys();
      c.setTimeInMillis(sys.getSunrise() * 1000);
      System.out.println("Sunrise : "
        + DATE_FORMATTER.format(c.getTime()));
      c.setTimeInMillis(sys.getSunset() * 1000);
      System.out.println("Sunset : "
        + DATE_FORMATTER.format(c.getTime()));
    }

  }

}

Execution of this code produces the following output :

gsonsample_output

Like you can see, parse JSON with Gson is a pleasure because library manage all the mapping process. If you use a tool like Jsonschema2Pojo to generate POJOs objects, it become quitte simple to parse JSON in Java and Android.