Good day all

I am having trouble parsing a JSONArray from a JSONObject. I might just be misunderstanding.

Creating the JSONObject to send:

int i = 0;
JSONArray jsonArray = new JSONArray();
String line;

while ((line = bufferedReader.readLine()) != null) {
    JSONObject rule = new JSONObject().put("rule", line);
    jsonArray.put(i,rule);
    i++;
}
return (new JSONObject().put(jsonStrings.REQUEST_RULES_ALL_RESPONSE, jsonArray));

This send a json array within a json object, to make things simpler. This is correct.

the returned object is in this format:

{"REQUEST_RULES_ALL_RESPONSE":[ 
        {"rule":"something"},
        {"rule":"something"},
        {"rule":"something"}  ]}

I would like to parse this into a List RULES. Reading the JSONObject recieved:

//this returns the object as described above
JSONObject jsonObject = serverData.SendData(new JSONObject().put(jsonStrings.REQUEST_RULES_ALL, " ")); 

//Trying to Convert to JSONArray, the get strings are correct, 
//notice the REQUEST and REQUEST RESPONSE.

//problem line below
JSONArray JSONFirewallRules = new JSONArray ((JSONArray)jsonObject.get(jsonStrings.REQUEST_RULES_ALL_RESPONSE));  

ERROR: org.json.JSONException: Not a primitive array: class org.json.JSONArray

I do not understand why this is a problem. I would like to get the JSONArray from the object.

  • jsonArray.put(i,rule); to jsonArray.put(rule); – Jois Mar 29 '16 at 8:34
up vote 3 down vote accepted

In the problematic line, instead of casting to a JSONArray, use getJSONArray:

JSONArray JSONFirewallRules = jsonObject.getJSONArray(jsonStrings.REQUEST_RULES_ALL_RESPONSE); 

However the exception isn't a cast exception, but a constructor exception where you are trying to build a JSONArray object from an unsupported list of items, which is another JSONArray :)

jsonObject.getJSONArray(key) throw exception in case key not found
Use jsonObject.opt... methods. These methods just return null if key not found in json object
Use jsonObject.optJSONArray(key) instead of jsonObject.getJSONArray(key)

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.