2

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
3
  • double check your string format Commented Jan 3, 2011 at 14:17
  • Actually you have no valid JSON. Strings and keys must be enclosed in double quotes ". But I don't know if this is enforced in Java's implementation. Commented Jan 3, 2011 at 14:18
  • No, single quotes are also fine. Commented Jan 3, 2011 at 14:45

2 Answers 2

5

'menuitem' is not a child of tmp. Try this:

js = tmp.getJSONObject("menu").getJSONObject("popup").getJSONArray("menuitem");
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.