Parsing JSON using Java and GSON library

In my previous post here, I gave a brief overview of JavaScript Object Notation (JSON). In this post I would go a bit further and show how one can parse the JSON documents into Java objects using the GSON library. The JSON data for this tutorial was obtained from: “https://api.twitter.com/1/users/show.json?screen_name=” where screen_name was TwitterAPI and sanaulla. So I condensed the data into the following:

also read:

 [
  {
    "id":"6253282",
    "name":"Twitter API",
    "screen_name":"twitterapi",
    "url":"http://dev.twitter.com",
    "followers_count":1004641,
    "friends_count":33,
    "favourites_count":24,
    "statuses_count":3277
  },
  {
    "id":"15082387",
    "name":"Sanaulla",
    "screen_name":"sanaulla",
    "url":"http://blog.sanaulla.info",
    "followers_count":241,
    "friends_count":302,
    "favourites_count":41,
    "statuses_count":1876
  }
]

Let me call this file as twitterUser.json. It is an array of user profile data where each user profile contains: name, id, screen_name, url, followers_count, friends_count, favourites_count and statuses_count. In order to run the following code, you need to download the GSON API jar from here and add it to your classpath. Moving further, we need to create a Model class which would hold the data obtained from JSON document.

 
/**
* Model class for storing the selected few attributes
* for a Twitter User profile.
*/
class TwitterUser{
  private String id;
  private String name;
  private String screen_name;
  private String url;
  private int friends_count;
  private int followers_count;
  private int favourites_count;
  private int statuses_count;
  public TwitterUser(){
  }
  @Override
  public String toString(){
    return "Name: "+this.name+"n" +
    "Screen Name: "+this.screen_name+"n" +
    "Number of Friends: "+ this.friends_count + "n" +
    "Number of Followers: "+ this.followers_count +"n" +
    "Number of Status updates: "+this.statuses_count +"n" +
    "Number of favorites: "+this.favourites_count +"n";
  }
}

Before putting forth the code, let me brief about the classes where are used for parsing the Json:

  • com.google.gson.Gson:
    This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it.
  • com.google.gson.JsonParser:
    A parser to parse Json into a parse tree of JsonElements
  • com.google.gson.stream.JsonReader:
    Reads a JSON encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays.
  • com.google.gson.JsonArray:
    A class representing an array type in Json. An array is a list of JsonElements each of which can be of a different type.
  • com.google.gson.JsonElement:
    A class representing an element of Json. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull.

Reading the JSON document using JsonReader, assuming the document is present in the file systems:

 JsonReader reader = new JsonReader(
        new InputStreamReader(new FileInputStream(this.jsonSource)));

JsonReader has a constructor which takes in an instance of a Reader, in our case we use the InputStreamReader and pipe it to a FileInputStream.

Once we are able to read the json data, we go ahead and use JsonParser to parse the contents and obtain the array of objects which the json document stores. There is an another way to do this with out using the JsonParser explicitly, but lets stick to this as its more clearer.

 
JsonParser jsonParser = new JsonParser();
JsonArray userarray= jsonParser.parse(jsonReader).getAsJsonArray();

parse(JsonReader) method of the JsonParser, parses the given Json and creates a parse tree of JsonElements. And the method getAsJsonArray() returns the parsed Json as an array of json objects. In our document we are sure that the document is an array of json objects (recall, the [ ] stands for representing the arrays in json). Suppose you were not sure if those are arrays, then you can use isJsonArray() method of the JsonElement class.

Next up, is to traverse through the array and populate the data from the json object in to our model bean TwitterUser which we had defined at the beginning.

 List twitterUsers = new ArrayList<>();
for ( JsonElement aUser : userArray ) {
TwitterUser aTwitterUser = myGson.fromJson(aUser, TwitterUser.class);
twitterUsers.add(aTwitterUser);
}

For each element in the JsonArray we use Gson.fromJson() to populate the data in the json object into the type defined by TwitterUser.class. How it works behind the scene is:

  • It creates a new instance of TwitterUser, by invoking the default constructor.
  • Sets the values of the attributes in the TwitterUser class with those obtained from the json array element. If you closely look at the names of the attributes in the TwitterUser class and the ones in the Json document- they are exactly similar- something like- screen_name, friends_count, followerr_count and so on.

The fromJson method in Gson has been overloaded to support multiple types of parameters, and from that we are using the fromJson(JsonElement json, Class<T> classOfT) version.

Now just to confirm we have parsed the correct data, iterate through the user list:

 for ( TwitterUser tUser : twitterUsers)
{
  System.out.println(tUser);
}

The complete source for the code is given below:

 import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class JsonParserDemo {

  private String jsonSource;
  private boolean sourceFromFile;
  public JsonParserDemo(String jsonSource, boolean sourceFromFile){
    this.jsonSource = jsonSource;
    this.sourceFromFile = sourceFromFile;
  }
  public static void main(String[] args){
    JsonParserDemo jsonParserDemo =
     new JsonParserDemo("/home/mohamed/twitterUser.json", true);
    try(JsonReader jsonReader = jsonParserDemo.getJsonReader()){
      Gson myGson = new Gson();
      JsonParser jsonParser = new JsonParser();
      JsonArray userArray =  jsonParser.parse(jsonReader).getAsJsonArray();
      List twitterUsers = new ArrayList<>();
      for ( JsonElement aUser : userArray ){
        TwitterUser aTwitterUser = myGson.fromJson(aUser, TwitterUser.class);
        twitterUsers.add(aTwitterUser);
      }
      for ( TwitterUser tUser : twitterUsers){
        System.out.println(tUser);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
  * Obtain the JsonReader for the given source details.
  * @return the JsonReader instance
  * @throws FileNotFoundException
  */
  private JsonReader getJsonReader () throws FileNotFoundException{
    JsonReader reader = null;
    if (sourceFromFile){
      reader = new JsonReader(
        new InputStreamReader(new FileInputStream(this.jsonSource)));
    }
    return reader;
  }
}

/**
* Model class for storing the selected few attributes
* for a Twitter User profile.
*/
class TwitterUser{
  private String id;
  private String name;
  private String screen_name;
  private String url;
  private int friends_count;
  private int followers_count;
  private int favourites_count;
  private int statuses_count;

  public TwitterUser(){
  }

  @Override
  public String toString(){
    return "Name: "+this.name+"n" +
      "Screen Name: "+this.screen_name+"n" +
      "Number of Friends: "+ this.friends_count + "n" +
      "Number of Followers: "+ this.followers_count +"n" +
      "Number of Status updates: "+this.statuses_count +"n" +
      "Number of favorites: "+this.favourites_count +"n";
  }
}

Comments

comments

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Comments

  1. Good Code Working fine!!!!

Trackbacks

  1. [...] Events in India and plots them on a Google Map. For reading the JSON source we would be using the GSON library. We have to update the contents of pom.xml to reflect the ZK, GSON and other dependencies. One can [...]

Speak Your Mind

*