1

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.

1
  • jsonArray.put(i,rule); to jsonArray.put(rule); Commented Mar 29, 2016 at 8:34

2 Answers 2

3

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

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.