How to convert nested Json string to Java object using Gson library

Default featured post

JSON is everywhere in back end programming, from various webservices, databases and so on.  Gson library is the one the most available libraries for Java which makes the conversion of JSON string to Java object hassle free and very easy. What do you all need to do is to download this library and add it to your Java project and then create a class for your JSON string in Java and map values one by one. Then using Gson convert the JSON string to Java object. That’s it.

In order to understand the situation better, let’s follow a real world example.

Assume we want to convert the result of Openweathermap.org Weather forecast web-service from JSON into Java object.

The result in JSON format is look like below,

{
"coord":{
"lon":-74.01,
"lat":40.71
},
"weather":[
{
"id":701,
"main":"Mist",
"description":"mist",
"icon":"50n"
}
],
"base":"stations",
"main":{
"temp":18.58,
"pressure":1006,
"humidity":88,
"temp_min":14,
"temp_max":22
},
"visibility":16093,
"wind":{
"speed":4.6,
"deg":230
},
"clouds":{
"all":90
},
"dt":1442643230,
"sys":{
"type":1,
"id":964,
"message":0.0155,
"country":"US",
"sunrise":1442659236,
"sunset":1442703496
},
"id":5128581,
"name":"New York",
"cod":200
}
view raw test.json hosted with ❤ by GitHub

As you can see, the result contains nested JSON and somehow array/list. Don’t worry, conversion for this case is quite easy as well.

Now, create a class in your Java project (e.g. class name : WebServiceResponseJson.java) and map the variable one by one from JSON string result in your Java object like the following,

import com.google.gson.annotations.SerializedName;
import java.math.BigDecimal;
import java.util.List;
public class WebServiceResponseJson {
@SerializedName("coord")
public Coord coord;
@SerializedName("weather")
public List<Weather> weather;
@SerializedName("base")
public String base;
@SerializedName("main")
public Main main;
@SerializedName("visibility")
public BigDecimal visibility;
@SerializedName("wind")
public Wind wind;
@SerializedName("clouds")
public Clouds clouds;
@SerializedName("dt")
public BigDecimal dt;
@SerializedName("sys")
public Sys sys;
@SerializedName("id")
public BigDecimal id;
@SerializedName("name")
public String name;
@SerializedName("cod")
public BigDecimal cod;
public static class Coord {
public BigDecimal lon;
public BigDecimal lat;
public Coord() {
this.lon = new BigDecimal(0);
this.lat = new BigDecimal(0);
}
}
public static class Weather {
public Integer id;
public String main;
public String description;
public String icon;
public Weather() {
this.id = new Integer(0);
this.main = "";
this.description = "";
this.icon = "";
}
}
public static class Main {
public BigDecimal temp;
public BigDecimal pressure;
public BigDecimal humidity;
public BigDecimal temp_min;
public BigDecimal temp_max;
public Main() {
this.temp = new BigDecimal(0);
this.pressure = new BigDecimal(0);
this.humidity = new BigDecimal(0);
this.temp_min = new BigDecimal(0);
this.temp_max = new BigDecimal(0);
}
}
public static class Wind {
public BigDecimal speed;
public BigDecimal deg;
public Wind() {
this.speed = new BigDecimal(0);
this.deg = new BigDecimal(0);
}
}
public static class Clouds {
public BigDecimal all;
public Clouds() {
this.all = new BigDecimal(0);
}
}
public static class Sys {
public BigDecimal type;
public BigDecimal id;
public BigDecimal message;
public String country;
public BigDecimal sunrise;
public BigDecimal sunset;
public Sys() {
this.type = new BigDecimal(0);
this.id = new BigDecimal(0);
this.message = new BigDecimal(0);
this.country = "";
this.sunrise = new BigDecimal(0);
this.sunset = new BigDecimal(0);
}
}
}

As you can see for nested values, I have defined an inner class to handle the situation and then use this class in either plane form or in form of list (to handle JSON array).

Now let’s move to the next part. After you called your webservice, you will get the result in JSON string form, now, you just need to convert it to Java object. In order to do that, you should use Gson library like below,

private WebServiceResponseJson parseJsonObj(String jsonString) {
WebServiceResponseJson result = null;
try {
Gson gson = new Gson();
result = gson.fromJson(jsonString, WebServiceResponseJson.class);
} catch (Exception ex) {
ex.printStackTrace();
}
}
view raw Test.java hosted with ❤ by GitHub

After that you can use the result of your webservice call easily via result class. For better understand you can have a look to this example on GitHub.