Sep 30, 2012

f Comment

Parsing JSON Response in Java in SECONDS!

Amazon If you are working on an Android social app using the Facebook SDK and you successfully use the Graph API to get information about the logged in user, you may run into the following question: how do I parse the JSON response? Since an Android app is written in Java my solutions will be Java code.

This article will help you parse simple JSON as well as complicated JSON!

JSON: key-value pairs
If the JSON response you are getting is as simple as a map such as the following:

{"id":"36241119","name":"Michael Wen","first_name":"Michael","last_name":"Wen"...}
Simply do the following to parse JSON to get the data you want:
try {
 JSONObject json = Util.parseJson(response);
 
 String[] data=new String[]{"id","name","first_name","last_name"};
 
 StringBuffer sb=new StringBuffer("User data:");
 for(String token:data){
  sb.append(" "+token+"="+json.getString(token));
 }
 Log.d("",sb.toString());
 
} catch (Exception e) {
 Log.e("","Error parsing JSON:"+e);
}
In this case JSON is just like a Map where you get the value by providing a key.

JSON: arrays of key-value pairs
If the JSON response contains an array of data such as the following:
{
   "data": [
      {
         "name": "\u5b8b\u67cf\u661f",
         "id": "36241119",
         "rsvp_status": "attending"
      },
      {
         "name": "Hung-Chang Lin",
         "id": "36241118",
         "rsvp_status": "attending"
      }
   ]
}
Getting the data you need may seem daunting at first but it's actually quite easy. Simply extract the array into an JSONArray object and loop through the array while getting the data of each element. Here's some sample code:
String[] data=new String[]{"id","name","rsvp_status"};

try {
 JSONObject json = Util.parseJson(response);
 JSONArray events=json.getJSONArray("data");
 for(int i=0; i<events.length(); i++){
  JSONObject event=(JSONObject)events.get(i);

  StringBuffer sb=new StringBuffer("Event #"+(i+1)+":");
  for(String token:data){
   sb.append(" "+token+"="+event.getString(token));
  }
  sb.append("\n\n");
  
  Log.d("",sb.toString());
 }
} catch (Exception e) {
 Log.e("","Error parsing JSON: "+e);
}
If you have any questions let me know and I will do my best to help you!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael