Wednesday, August 25, 2010

JSON parsing in android

 AIM:To parse a Json string in android.
Solution:
 Step 1 ) Declare the json string .

                JSONObject jObject;
String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\",   \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";

Step 2)  convert jString to the jObject by 
              jObject = new JSONObject(jString);
Step 3) Lets extract the menu object by creating a new menu object,
                        JSONObject menuObject = jObject.getJSONObject("menu");
 extract the attributes as follows:
String attributeId = menuObject.getString("id");
Log.i("attributeID:",""+attributeId);
                       String attributeValue = menuObject.getString("value");
                       Log.i("attributeValue:",""+attributeValue);

Ste 4) Final code:


private void JsonParsing() {
JSONObject jObject;
String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\",   \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
try {
jObject = new JSONObject(jString);

JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);

String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);

JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");

for (int i = 0; i < 3; i++) {
Log.i("Value",menuitemArray.getJSONObject(i)
.getString("value").toString());
Log.i("Onclick:", menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}



No comments:

Post a Comment

Android Developers Blog

Ram's shared items