Parsing JSON String in Android

Suppose i store my JSON response in string response.
String response = {
    "name": "John Smith",
    "age": 32,
    "employed": true,
    "address": {
        "street": "701 First Ave.",
        "city": "Sunnyvale, CA 95125",
        "country": "United States"
    "children": [
            "name": "Richard",
            "age": 7
            "name": "Susan",
            "age": 4
            "name": "James",
            "age": 3

{ = This sign respresent that it is JSONObject node.
 [= This sign represnt that it is JSON Array node.

 so we will parse the response in this way,

 JSONObject objres = new JSONObject(response);

   String Name =objres.getString("name").// it will fetch name and store its value in variable Name.

   String Age =objres.getString("age").// it will fetch age and store its value in variable Age.

   String Employed =objres.getString("employed").// it will fetch employed and store its value in variable Employed.

  Note:  "address": { is an JSONObject node inside object objres.

   JSONObject objAddress = objres.getJSONObject(address);

       String Street =objAddress.getString("street").// it will fetch street and store its value in variable Street

       String City =objAddress.getString("city").// it will fetch city and store its value in variable City

   Note:  "children": [ is an JSONArray inside object objres.

       JSONArray childrenArray = objres.getJSONArray("children");

       //Following code will give value of  element at zeroth  to last position in array..suppose i am having more than 1 element in array so i will use for loop to get value of each element.

       for (int J = 0; J < childrenArray.length(); J++) {

       JSONObject menuObject = childrenArray.getJSONObject(J);

       String chName= menuObject.getString("name");
       String chAge= menuObject.getString("age");


Popular Posts