简体   繁体   English

从JSONObject创建JSONArray

[英]create JSONArray from JSONObject

Good day all 大家好

I am having trouble parsing a JSONArray from a JSONObject. 我无法从JSONObject解析JSONArray。 I might just be misunderstanding. 我可能只是误会了。

Creating the JSONObject to send: 创建要发送的JSONObject:

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. 这将在json对象内发送一个json数组,使事情变得更简单。 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: 读取收到的JSONObject:

//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 错误:org.json.JSONException:不是原始数组:类org.json.JSONArray

I do not understand why this is a problem. 我不明白为什么这是一个问题。 I would like to get the JSONArray from the object. 我想从对象获取JSONArray。

In the problematic line, instead of casting to a JSONArray, use getJSONArray: 在有问题的行中,而不是强制转换为JSONArray,请使用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 :) 但是,该异常不是强制转换异常,而是构造函数异常,在该异常中,您尝试从不受支持的项目列表(这是另一个JSONArray)中构建JSONArray对象:)

jsonObject.getJSONArray(key) throw exception in case key not found jsonObject.getJSONArray(key)引发异常
Use jsonObject.opt... methods. 使用jsonObject.opt ...方法。 These methods just return null if key not found in json object 如果在json对象中找不到密钥,则这些方法仅返回null
Use jsonObject.optJSONArray(key) instead of jsonObject.getJSONArray(key) 使用jsonObject.optJSONArray(key)代替jsonObject.getJSONArray(key)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM