簡體   English   中英

如何訪問 Apex 中的嵌套 JSON?

[英]How to access nested JSON in Apex?

我是 Apex 的新手,如果您能在以下方面提供幫助,我將不勝感激:

下面的代碼從輸入返回整個列表:

public static string input ='[{"item1": 1,"item2": "2","item3": [{"child1": "11","child2": "22","child3": 33}]},{"item1": "aa","item2": "bb","item3": [{"child1": "22","child2": "33","child3": 12}]}]';

List<Object> jsonParsed = (List<Object>) JSON.deserializeUntyped(input);
System.debug(jsonParsed);

我想得到“item3”的孩子,以便我可以閱讀:

“item1”:“1” “child1”:“11” “child2”:“22” “child3”:33

我已經嘗試了下面的代碼但沒有成功,我得到 item1 但孩子 1,2 和 3 為空。

for(Object jsonParsed : jsonParsed){
        Map<String,Object> ind = (Map<String,Object> )jsonParsed;
        System.debug('item1 = '+ ind.get('item1'));        
        System.debug('child1 = '+ ind.get('item3.child1[0]'));
        System.debug('child2 = '+ ind.get('item3.child2[1]'));
        System.debug('child3 = '+ ind.get('item3.child3[2]'));
    }

Apex 不支持get()方法中的關系路徑或表達式,如下所示:

    System.debug('child1 = '+ ind.get('item3.child1[0]'));

那只會返回null

您必須按順序訪問 JSON 中每個級別的結構,如果您使用deserializeUntyped()您還必須在每個級別轉換數據結構(因為get()返回泛型類型Object ):

    Map<String, Object> item3 = (Map<String, Object>)ind.get('item3');
    List<Object> child1 = (Map<String, Object>)item3.get('child1');
    Object child1Item = child1[0];

    System.debug('child1 = ' + child1Item);

在可能的情況下,定義一個表示 JSON 的強類型 Apex 類並將其反序列化為該類通常要容易得多。 您的 JSON 在這里足夠通用,我不知道該怎么做; 您需要查看實際的數據類型和鍵,並考慮使用JSON2Apex 之類的工具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM