Java: Parsing JSON with Google’s Gson Library
This post serves as a follow-up to A Simple REST Client, in which a basic REST client for the Facebook Graph API was created. In this post, a few examples will show how to get started with Gson by doing some simple parsing of JSON (JavaScript Object Notation) returned by the Facebook Client.
Pre-requisites
JSON Parser
In order to be able to pass the data around in a more object-oriented manner, I first created an object to represent (a small part of) a Facebook Object:
This is a simple class that contains only the fields that I needed for manipulating Facebook Objects in this example, i.e. name
and id
.
Next comes the controller class that does the actual parsing with Gson. This is the constructor:
The two global references are to the REST client object and one to a JsonParser
, which as its name suggests, facilitates creating Gson objects from the raw Strings returned from the client’s methods.
Below are a few methods that show what can be done with the library.
Method: getNameForId()
public String{// Perform the API request and parse the data.String data = client.;JsonObject json = (JsonObject)parser.;// Confirm that the member exists.return ((json.) ? json.. : "");}
This is a method that takes in an id of a Facebook Object and returns the name if the object exists, else an empty String. As a reminder, the format of the data returned from Facebook is as follows:
{"id": "273100900","name": "Christian Evans","first_name": "Christian","last_name": "Evans","username": "ceva24","gender": "male","locale": "en_GB"}
This is a standard JSON object with seven key-value pairs. Thus we see that the data parsed with the JsonParser
is cast as a JsonObject
with the following line:
JsonObject json = (JsonObject)parser.;
By examining the documentation of JsonObject
we can see there are has
and get
methods, for checking whether a pair exists and retrieving the value for a key respectively. Thus we can say if the key “name” exists, retrieve its value:
return ((json.) ? json.. : "");
Get returns a JsonElement object; by calling getAsString()
on this, we can retrieve the value in String format (which in this case strips the quotation marks from the value, and would transform it to a String if it were e.g. an int or boolean).
Method: getLikes()
public List<facebookobject>{final List<facebookobject> result = new ArrayList<>();// client.getObjectLikes requires authentication.if (!client.)client.;// Perform the API request and parse the data.String data = client.;JsonObject json = (JsonObject)parser.;JsonArray dataArray = json.;// Loop through each Facebook object and add its name to the list.for (JsonElement e : dataArray){JsonObject o = e.;// Confirm that the members exist.String objectId = ((o.) ? o.. : "");String objectName = ((o.) ? o.. : "");result.;}return result;}
This method takes in a Facebook Object id and returns its likes as a List
of FacebookObject
s. Recall that due to security limitations, this method only functions for public pages.
Data is returned in the following format:
The JSON array, marked by [
and ]
, is the information that needs to be extracted in this case.
The String is cast to a JsonObject
as normal, and then a method is called to retrieve the value of “data”, which is the array.
JsonArray dataArray = json.;
JsonArray
implements Iterable
, which means we can use the enhanced for loop construct to loop through each item.
From looking at the data, we can see that the values of “data” don’t have any nested values, so they can themselves be cast as JsonObject
s. After that its just a case of extracting and returning the relevant data.
Method: getSixDegrees()
Next is something a little more interesting. Building upon the previous example, this next method attempts to iterate through six degrees of likes. If ever a page is reached that doesn’t return any likes, null objects are returned for the remaining entries.
public FacebookObject[]{final FacebookObject[] result = new FacebookObject[6];final Random randomGenerator = new Random();// Loop through up to 6 FacebookObjects, tracking their id for the next iteration.for (int i = 0; i < 6; i++){List<facebookobject> likes = this.;// Quit out if a dead end is reached.if (likes.)break;// Get a random like. Passing 0 to nextInt() is not allowed.FacebookObject degree = likes. == 1 ?likes. :likes.;id = degree.; // Prepare for the next loop.result[i] = degree;}return result;}
Results
Putting it all together, here’s a Main class that runs all of the above methods.
And the results:
Christian Evans123355014367126, Atlanta Food & Wine Festival69421318512, Six Flags Great Adventure32237381874, Kings Dominion42125257610, ESSENCE Music Festival6243987495, Spotify287552055150, Coca-Cola light61124008229, Coca-Cola Zero23550666633, Fanta66681829158, Sprite8605796091, Diet Coke5120148605, will.i.am6243987495, Spotify77589292295, Chevrolet8280904159, Eli ManningYou only reached the 3rd degree! Better luck next time!
And there we have it. Hopefully this post has given some insight into how to parse JSON in an object-oriented manner using Google’s Gson library.
Thanks for reading!
Update: Source files are now on Github, along with corresponding unit tests.