Please advice why开发者_开发知识库 I'm getting an exception on trying to create a JSONArray instance?
String task = "{'menu': { 'id': 'file', 'value': 'File', 'popup': { 'menuitem': [ {'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}] }}}";
try {
JSONObject tmp = new JSONObject(task);
js = tmp.getJSONArray("menuitem"); // exception fires here
} catch(JSONException e) {
e.printStackTrace();
}
Getting an exception
01-03 16:12:17.926: WARN/System.err(5999): org.json.JSONException: No value for menuitem
'menuitem' is not a child of tmp
. Try this:
js = tmp.getJSONObject("menu").getJSONObject("popup").getJSONArray("menuitem");
For me it worked like this:
JSON file:
{
"response":
{
"results":
[
{
"value1":"1",
"value2":"2"
},
{
"value1":"1",
"value2":"2"
}
],
"status":
{
"code":"200",
"message":"Success"
}
}
}
Then:
JSONArray array = responseObject.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
// CREATE YOUR OBJECTS
}
精彩评论