2016-03-08 2155 views
0

我試圖解析以下類型JSONArray的:如何判斷我的JSONArray是否包含某個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」 ,「蘋果電腦」: [ 「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()的東西嗎?

+1

在執行任何進一步操作之前,只需先獲取'attachmentPoint'並檢查其是否爲null。 'JSONArray attachmentPoint = fldevices.getJSONObject(i).getJSONArray(「attachmentPoint」);如果(attachmentPoint!= null){...}' – Braj

+0

「有沒有類似於.has()的數組」 - 你試過'fldevices.getJSONObject(i).has(「attachmentPoint」)'? – Thomas

+0

謝謝@Braj那完美的工作! – Fama

回答

0

使用has方法檢查是否存在attachmentPoint

E.g. :

if(fldevices.getJSONObject(i).has("attachmentPoint")){ 
    //process attachmentPoint 
} 
+0

我的不好,它實際上總是存在,但我需要檢查它是否是空的。我沒有設法用.has來做,但檢查它是否爲空或不工作。 – Fama

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。 如果路徑無效,則返回空值。 永不拋出異常。

例如

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) 
相關問題