我有一个自定义的 Salesforce 对象 Category__c,它可以自我查找多达 3 个级别。我已经编写了下面的代码来从这个对象构造一个 JSON。但我面临一个运行时错误:
System.JSONException:当前上下文不是数组而是对象
有人可以指出我在那里出错的地方。
我发现以下帖子与此错误相关,但我无法与之相关,因为它位于不同的平台上。 ElasticSearch:尝试索引数组时当前上下文不是数组而是对象
顶点代码:
public class lsRestResourceHandler {
public static String getCategoriesJSON() {
boolean l2fieldset = false;
//Query list of Categories
list<Category__c> lstCategories = new list<Category__c>([SELECT Parent_Category__r.Level__c
, Parent_Category__r.Id
, Parent_Category__r.Name
, Level__c
, Id
, Name
, (SELECT Level__c, Id, Name FROM SubCategories__r)
FROM Category__c WHERE Level__c=2 OR Level__c=1]);
Set<Id> setParentCategories = new Set<Id>();
for(Category__c category:lstCategories) {
setParentCategories.add(category.Parent_Category__r.Id);
}
//Start JSON Generator
JSONGenerator categoryJSON = JSON.createGenerator(true);
categoryJSON.writeStartObject();
categoryJSON.writeFieldName('Categories');
categoryJSON.writeStartArray();
//Iterate through 1st level1 Categories
for(Category__c level1:lstCategories) {
if(level1.Level__c == 1){
categoryJSON.writeStartObject();
categoryJSON.writeStringField('Id',level1.Id);
categoryJSON.writeStringField('Name',level1.Name);
if(setParentCategories.contains(level1.Id)) {
categoryJSON.writeFieldName('SubCategories');
categoryJSON.writeStartArray();
for(Category__c level2:lstCategories) {
//If Level1 is parent category for any level2 categories, iterate through them
if(level1.Id == level2.Parent_Category__r.Id) {
categoryJSON.writeStartObject();
categoryJSON.writeStringField('Id',level2.Id);
categoryJSON.writeStringField('Name',level2.Name);
//If level2 category has level3 SubCategories, iterate through them
if(level2.SubCategories__r != null) {
categoryJSON.writeFieldName('SubCategories');
categoryJSON.writeStartArray();
for(category__c level3:level2.SubCategories__r) {
categoryJSON.writeStartObject();
categoryJSON.writeStringField('Id',level3.Id);
categoryJSON.writeStringField('Name',level3.Name);
categoryJSON.writeEndObject();
}
categoryJSON.writeEndArray();
}
categoryJSON.writeEndObject();
}
}
categoryJSON.writeEndArray();
categoryJSON.writeEndObject();
}
}
}
categoryJSON.writeEndArray();
categoryJSON.writeEndObject();
//Convert to JSON String
String strCategoryJSON = categoryJSON.getAsString();
return strCategoryJSON;
}
}
目标 JSON 格式:
{
"Categories":[
{
"Id":"5",
"Name":"Category5",
"SubCategories":[
{
"Id":"51",
"Name":"Cat5Sub1",
"SubCategories":[
{
"Id":"511",
"Name":"Cat5Sub1Sub1"
},
{
"Id":"512",
"Name":"Cat5Sub1Sub1"
}
]
},
{
"Id":"32",
"Name":"Cat5Sub2",
"SubCategories":[
{
"Id":"511",
"Name":"Cat5Sub1Sub2"
},
{
"Id":"512",
"Name":"Cat5Sub1Sub2"
}
]
},
{
"Id":"33",
"Name":"Cat5Sub3"
}
]
}
]
}