【发布时间】: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