Saturday, December 24, 2011

Google's GSON library to parse JSON

Google's OAuth 2.0 library returns access token related information in JSON format as shown in the sample below:


{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"
}


I was looking for a library to parse JSON and stumbled across GSON, which was very straightforward to use. The library has methods to create a java object from JSON or JSON from a java object. The sample program below shows how to do the former.

Download GSON library from here.

Create a class that can be used to create java objects to hold converted JSON.



public class GoogleAccessToken {
String access_token;
String refresh_token;
String token_type;
int expires_in;
@Override
public String toString() {
return "access_token: " + access_token + "refresh_token: " + refresh_token +" - " + "token_type:"+ token_type + " - " + "expires_in:" + expires_in;
}
public String getAccessToken() {
return access_token;
}
public String getRefreshToken() {
return refresh_token;
}
public String getTokenType() {
return token_type;
}
public int getExpiresIn() {
return expires_in;
}
}


Assume myJsonString variable has the JSON that needs to be parsed.

Gson gson = new GsonBuilder().create();
GoogleAccessToken jsonObject = gson.fromJson(myJsonString,GoogleAccessToken.class)



Now that the JSON is converted to java object form, you can access it's variables using the accessor functions.

jsonObject.toString()
//the above line prints the following: 
//access_token: 1/fFAGRNJru1FTz70BzhT3Zg refresh_token: - token_type: Bearer - expires_in: 3920