Tuesday 4 June 2013

JSON Parsing in Android

JSON parsing is just a cakewalk once you are familiar with JSON format

Generally JSON response consists of :

1.)  Objects
2.)  Array of Objects

Each object has its attributes as name : value pair.
Object, called as JSONObject, starts with { and array, called as JSONArray, starts with [.

For example :

a.) JSON Structure Example
To parse a response that looks like array example above :




1.) Use jObj.getJSONArray("arrayName") to retrieve the array

2.) Iterate over all the objects in that array using length()

3.) Fetch each object

4.) Retrieve each item of object (retrieved as name-value pair) using getString("name") or other appropriate method

5.) In case there is a single object, it can be retrieved directly using step 3, and if there is only name-value pair, use step 4.

Here, jObj is the JSONObject – the response obtained after executing HTTP Post request.

A quick look at how its done :

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(“URL”);
HttpEntity entity = null;
String json = "";
JSONObject jObj = null;

//Add your data, if any, for the request
List pairs = new ArrayList();
pairs.add(new BasicNameValuePair("sample", “sample”));
post.setEntity(new UrlEncodedFormEntity(pairs));

//Execute the request
HttpResponse response = client.execute(post);  

//Retrieve the response which is InputStreamReader

entity = response.getEntity();
InputStreamReader is = new InputStreamReader(entity.getContent(), "UTF-8");
if (is != null) {
        BufferedReader reader = new BufferedReader(is);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) 
       {
        sb.append(line + "\n");
       }
       json = sb.toString();
       jObj = new JSONObject(json);
}

PS :  HTTP Post request should be used in non-UI thread (use AysncTask) .


~Divya