我正在尝试使用 json-lib jar 解析一个简单的 json 数据。JSON数据具有以下格式:
{"plantDetails":
[{
"common":"New Plant 1",
"botanical":"",
"light":"Mostly Shady",
"price":0,
"availDate":"10/25/2012",
"indoor":false,
"id":null
},{
"common":"New Plant 1",
"botanical":"",
"light":"Mostly Shady",
"price":0,
"availDate":"10/25/2012",
"indoor":false,
"id":null
},{
"common":"New Plant 1",
"botanical":"",
"light":"Mostly Shady",
"price":0,
"availDate":"10/25/2012",
"indoor":false,
"id":null
}]
}
为此,我使用以下代码:
try {
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jb.toString());
JSONArray arr = jsonObject.getJSONArray("plantDetails");
//net.sf.json.JSONObject jsonObject1 = jsonObject.getJSONObject("plantDetails");
Iterator iter = arr.iterator();
while (iter.hasNext()) {
JSONObject object = (JSONObject) iter.next();
System.out.println(object.getString("common"));
System.out.println(object.getString("botanical"));
}
} catch (Exception e) {
// crash and burn
System.out.println(e.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
当有多个 JSONObject(在我的情况下为 3 个)时,此代码可以正常工作。但不幸的是,当 JSON Object 的数量只有 1 时它不起作用。它抛出异常:net.sf.json.JSONException:
JSONObject["plantDetails"] is not a JSONArray.
如何检查是否存在多个 JSONObject?
解决此问题的一种方法是在仅一个 JSONObject 的 try/catch 块中引发上述异常后使用这段代码,然后获取相应的值:
net.sf.json.JSONObject jsonObject1 = jsonObject.getJSONObject("plantDetails");
但我不想这样:
1)可能有一些更好的方法来实现相同的目标,而不是捕获异常并处理它以获取 Object 值
2)需要知道实现相同目标的最佳方法
请让我知道这件事。
问候,