【问题标题】:create JSONArray from JSONObject从 JSONObject 创建 JSONArray
【发布时间】:2016-03-29 08:30:40
【问题描述】:

大家好

我在从 JSONObject 解析 JSONArray 时遇到问题。我可能只是误会了。

创建要发送的 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));

这会在 json 对象中发送一个 json 数组,以使事情变得更简单。这是正确的。

返回的对象格式如下:

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

我想将其解析为列表规则。 读取收到的 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));  

错误:org.json.JSONException:不是原始数组:类 org.json.JSONArray

我不明白为什么这是个问题。我想从对象中获取 JSONArray。

【问题讨论】:

  • jsonArray.put(i,rule);到 jsonArray.put(rule);

标签: java json


【解决方案1】:

在有问题的行中,不要强制转换为 JSONArray,而是使用 getJSONArray:

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

但是,该异常不是强制转换异常,而是构造函数异常,您尝试从不受支持的项目列表构建 JSONArray 对象,这是另一个 JSONArray :)

【讨论】:

    【解决方案2】:

    jsonObject.getJSONArray(key) 在找不到密钥的情况下抛出异常
    使用 jsonObject.opt... 方法。如果在 json 对象中找不到键,这些方法只会返回 null
    使用jsonObject.optJSONArray(key) 而不是jsonObject.getJSONArray(key)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 2017-03-19
      相关资源
      最近更新 更多