• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Parsing JSON using Java and GSON library

April 30, 2012 //  by Mohamed Sanaulla//  Leave a Comment

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:

also read:

  • JSON Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials
 [
{
"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 =&amp;amp;nbsp; jsonParser.parse(jsonReader).getAsJsonArray();
List twitterUsers = new ArrayList&amp;amp;lt;&amp;amp;gt;();
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";
}
}

Category: JavaTag: gson, JSON

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.

Previous Post: «json What is JSON?
Next Post: Parsing JSON using Groovy »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact