我正在尝试解析以下类型的JSONArray:
[{ “entityClass”: “DefaultEntityClass”, “MAC”:[ “86:2B:A2:F1:2B:图9c”], “IPv4的”:[ “10.0.0.1”], “IPv6的”:[ ], “VLAN”:[ “为0x0”], “attachmentPoint”:[{ “switchDPID”: “00:00:00:00:00:00:00:02”, “端口”:1, “的ErrorStatus”:空}], “lastSeen”:1456312407529},{ “entityClass”: “DefaultEntityClass”, “MAC”:[ “1E:94:63:67:1E:D1”], “IPv4的”:[ “10.0.0.3” ],的 “IPv6”:[], “VLAN”:[ “为0x0”], “attachmentPoint”:[{ “switchDPID”: “00:00:00:00:00:00:00:03”, “端口” :1, “的ErrorStatus”:空}], “lastSeen”:1456312407625},{ “entityClass”: “DefaultEntityClass”, “MAC”:[ “06:D7:E0:C5:60:86”], “IPv4的” :[ “10.0.0.2”], “IPv6的”:[], “VLAN”:[ “为0x0”], “attachmentPoint”:[{ “switchDPID”:“00:00:00:00:00:00:00 :02" , “端口”:2 “的ErrorStatus”:空}], “lastSeen”:1456312407591},{ “entityClass”: “DefaultEntityClass”, “MAC”:[“6E:C3:E4:5E:1F: 65 “],” IPv4的 “:[” 10.0.0.4 “],” IPv6的 “:[],” VLAN “:[” 为0x0 “],” attachmentPoint “:[{” switchDPID “:” 00:00:00: 00:00:00:00:03" , “端口”:2 “的ErrorStatus”:空}], “lastSeen”:1456312407626}]
问题是,有时会出现“attachmentPoint”JSONArray,有时却没有。如果不存在,我会在输出中得到令人讨厌的异常文本。在尝试运行代码之前,如何检查它是否存在?
我目前有以下内容:
if (fldevices.getJSONObject(i).getJSONArray("attachmentPoint").getJSONObject(0).has("switchDPID")
但显然这不起作用,因为它已经尝试访问attachmentPoint,如果它不存在,我会收到错误。是否有类似于.has()的数组?
答案 0 :(得分:0)
使用has
方法检查是否存在attachmentPoint
。
E.g。 :
if(fldevices.getJSONObject(i).has("attachmentPoint")){
//process attachmentPoint
}
答案 1 :(得分:0)
尝试这种方法。
public static Object opt(Object json, String path) {
for (String key : path.split("\\.")) {
if (json == null)
return null;
if (json instanceof JSONArray) {
if (!key.matches("\\d+"))
return null;
json = ((JSONArray)json).opt(Integer.parseInt(key));
} else if (json instanceof JSONObject) {
json = ((JSONObject)json).opt(key);
} else
return null;
}
return json;
}
此方法按路径检索JSONObject或JSONArray。 如果路径无效,则返回null。 永远不会抛出异常。
例如
System.out.println(opt(fldevices, "0.attachmentPoint.0.switchDPID"));
System.out.println(opt(fldevices, "0.INVALID_KEY.0.switchDPID"));
System.out.println(opt(fldevices, "0.attachmentPoint.999.switchDPID"));
输出
00:00:00:00:00:00:00:02
null
null
所以你可以这样写。
if (opt(fldevices, i + ".attachmentPoint.0.switchDPID") != null)