亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不多次調用 .getJSONObject的情況下檢查 JSONObject 中是否存在屬性?

如何在不多次調用 .getJSONObject的情況下檢查 JSONObject 中是否存在屬性?

qq_花開花謝_0 2022-08-17 16:07:52
我正在處理深度嵌套的 JSON 數據。下面是一個簡短的示例:{     "timestamp":"123",   "layers":{        "frame_raw":"123",      "frame":{           "frame_frame_interface_id":"0",         "frame_interface_id_frame_interface_name":"asd",         ...      },      "eth_raw":"123",      "eth":{           "eth_eth_dst_raw":"asd",         "eth_eth_dst":"asd",         ...      },      "ip_raw":"123",      "ip":{           "ip_ip_version_raw":"4",         "ip_ip_version":"4",         "ip_ip_addr_raw":[              "asd",            "asd"         ],         "ip_ip_addr":[              "1.1.1.1",            "1.1.1.1"         ],         "ip_ip_dst_host":"1.1.1.1"      }      ...   }   ...}我有一個我明確允許的結構列表。應從 JSON 中刪除所有其他內容。列表示例:###frame###layers.frame_raw###eth###layers.eth.eth_eth_dstlayers.eth.eth_eth_src###ip###layers.ip.ip_ip_srclayers.ip.ip_ip_dstlayers.ip.ip_ip_src_hostlayers.ip.ip_ip_dst_hostlayers.ip.ip_ip_versionlayers.ip.ip_ip_hdr_lenlayers.ip.ip_ip_dsfield我的問題是,我只能使用“getJSONObject(key)”瀏覽JSON結構。如何以“key.key.key...”的形式生成JSON結構中最低元素的路徑。以便我可以將其與我的列表匹配?
查看完整描述

3 回答

?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

JSON 對象有一個名為 .has 的方法,它將返回一個布爾值。因此,邏輯類似于檢查 JSON 對象是否存在。如果是這樣,請檢查子節點是否存在更多數據。如果存在數組,則必須獲取該數組并使用任何循環在數組中遷移,并執行相同的操作。例如:


   if (json.has("ip")) {

        JSONObject jsonObject = getJSONObject.getString("ip")

        String ip_ip_version_raw = jsonObject.getString("ip_ip_version_raw"));

        if (jsonObject.has("ip_ip_addr_raw")){

            JSONArray ip_ip_addr_raw = jsonObject.getJSONArray("ip_ip_addr_raw");

            for (String s : ip_ip_addr_raw) {

                ...

            }

        } 

    }

參考資料:


http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)


查看完整回答
反對 回復 2022-08-17
?
DIEA

TA貢獻1820條經驗 獲得超2個贊

我找到了一個解決方案,因為我的特殊情況下的結構總是,所以結構的深度總是相同的,而不是可變的。layers.layer.property


對于感興趣的人:


for (Iterator<String> layersIterator = jsonObject.getJSONObject("layers").keys(); layersIterator.hasNext(); ) {

    String layer = layersIterator.next();

    for (Iterator<String> propertyIterator = jsonObject.getJSONObject("layers").getJSONObject(layer).keys(); propertyIterator.hasNext(); ) {

        String property = propertyIterator.next();

        System.out.println("layers."+layer+"."+property);

    }

}


查看完整回答
反對 回復 2022-08-17
?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

如果要檢查屬性是否存在,則有一個名為 的方法。這是官方文檔的鏈接。JSONObjecthas



查看完整回答
反對 回復 2022-08-17
  • 3 回答
  • 0 關注
  • 272 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號