如何使用Apex从嵌套JSON读取值?

问题描述

我正在将JSON字符串从Javascript传递到Apex。对于每个“字段”实例,我要访问的字段分别是“名称”和“ Content_Copy__c”,但我似乎无法弄清楚。我的一部分认为我需要创建一个地图,但是我也不确定该怎么做。在try-catch中,try无效,我认为这是问题的一部分,因为它进入了catch。

String jsonListString = '[{"fields":{"Name":"Step 1","Content_Copy__c":"lorem"}},{"fields":{"Name":"Step 2","Content_Copy__c":"ipsum"}}]';
Object o = JSON.deserializeUntyped(jsonListString);
try{
    Map<String,Object> m = (Map<String,Object>) o;
    System.debug('The Map is: ' + m);
}
catch(TypeException e){
    List<Object> a = (List<Object>) o;   
    for(Object obj : a){
        Map<String,Object> mapObject = (Map<String,Object>) obj;
        Object s = mapObject.get('fields');
        System.debug(s);
    }
}

上面的代码在打印到调试器时会给出以下结果。

Results of the for-loop showing the field values

编辑:在@Moustafa Ishak的建议下,我已经改变了周围的样子:

public class fields{
    public String Name {get; set;}
    public String Content_Copy {get; set;}

    public fields(String Name,String Content_Copy){
        this.Name = Name;
        this.Content_Copy = Content_Copy;
    }
}

String jsonListString = '[{"fields":{"Name":"Step 1","Content_Copy":"lorem"}},"Content_Copy":"ipsum"}}]';
List<fields> response = (List<fields>)System.JSON.deserialize(jsonListString,List<fields>.class);
for(fields f : response){
    System.debug('Name: ' + f.Name);
    System.debug('Content_Copy: ' + f.Content_Copy);
}

哪个给了我空值,如下所示。我必须将“ Content_Copy__c”更改为“ Content_Copy”,因为Apex的非自定义对象以“ __c”结尾存在问题。一旦获得字段的值,那将不是问题。如果我添加或删除另一个“字段”条目,则上面的代码可以识别,但是无法识别“名称”和“ Content_Copy”的值。

Null output

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)