如何在 Apex 中访问嵌套的 JSON?
How to access nested JSON in Apex?
我是 Apex 的新手,希望能在以下方面提供帮助:
下面的代码 returns 输入的整个列表:
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" 的 child,这样我就可以阅读:
"item1": "1" "child1": "11" "child2": "22" "child3": 33
我已经尝试了下面的代码但没有成功,我得到了 item1 但 child 1,2 和 3 为 null。
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]'));
那只会 return null
.
你必须按顺序访问JSON中的每一层结构,如果你正在使用deserializeUntyped()
你还必须在每一层转换数据结构(因为get()
returns 泛型类型 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 class 并将其反序列化通常要容易得多。您的 JSON 在这里足够通用,我不知道该怎么做;您需要查看实际的数据类型和键,并考虑使用 JSON2Apex.
之类的工具
我是 Apex 的新手,希望能在以下方面提供帮助:
下面的代码 returns 输入的整个列表:
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" 的 child,这样我就可以阅读:
"item1": "1" "child1": "11" "child2": "22" "child3": 33
我已经尝试了下面的代码但没有成功,我得到了 item1 但 child 1,2 和 3 为 null。
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]'));
那只会 return null
.
你必须按顺序访问JSON中的每一层结构,如果你正在使用deserializeUntyped()
你还必须在每一层转换数据结构(因为get()
returns 泛型类型 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 class 并将其反序列化通常要容易得多。您的 JSON 在这里足够通用,我不知道该怎么做;您需要查看实际的数据类型和键,并考虑使用 JSON2Apex.
之类的工具