【问题标题】:How to read values from nested JSON using Apex?如何使用 Apex 从嵌套 JSON 中读取值?
【发布时间】:2020-08-16 22:25:49
【问题描述】:

我将 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);
    }
}

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

编辑:在@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"}},{"fields":{"Name":"Step 2","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”结尾的非自定义对象的问题。一旦我获得了字段的值,这将不是问题。如果我添加或删除另一个“字段”条目,上面的代码会识别,但不会识别“Name”和“Content_Copy”的值。

【问题讨论】:

    标签: json salesforce apex


    【解决方案1】:

    您可以尝试创建如下响应包装器

    public class response{
    public String Name {get; set;}
    public String Content_Copy {get; set;}
    
    public response(String Name, String Content_Copy){
        this.Name = Name;
        this.Content_Copy = Content_Copy;
    }
    
    
    public class responseWrapper{
    
    public response fields {get; set;}
    
    }
    
    }
    

    然后您可以使用标准 JSON.deserialize 来获取响应包装器(字段)的列表

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

    【讨论】:

    • 我听从了您的建议,但两个值都为“null”。我已经编辑了我的原始帖子以显示这一点。
    • @ThatBrayKid 我已经更新了现在应该可以使用的答案
    猜你喜欢
    • 2023-03-14
    • 2019-07-31
    • 1970-01-01
    • 2020-11-09
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多