Categories
Java

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

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,

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,

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,

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.

Exit mobile version