APEX:如何将嵌套的父子关系序列化为JSON?

时间:2013-01-15 20:25:29

标签: salesforce force.com soql

在FinancialForce中,我有一个对象pse__Project_Task__c,可以与自身(其父级)相关,N级别深。我希望能够提取我的所有任务并将它们序列化为JSON:

[
    { 
        "TaskId" : "1",
        "TaskName" : "Parent 1",
        "children" : [
            { 
                "TaskId" : "2",
                "TaskName" : "Child 1.1",
                "children" : []
            },
            { 
                "TaskId" : "3",
                "TaskName" : "Child 1.2",
                "children" : [
                    { 
                        "TaskId" : "4",
                        "TaskName" : "Child 1.2.1",
                        "children" : []
                    }
                ]
            }
        ]
    },
    {
        "TaskId" : "5",
        "TaskName" : "Parent 2",
        "children" : []
    }
]

我已经创建了一个SOQL语句来获取我的任务,并创建了一个包装类来包装每个任务:

  public class TaskHeirarchyWrapper {

    public String TaskId {get; set;}
    public String TaskName {get; set;}
    public List<TaskHeirarchyWrapper> children {get; set;}

    public TaskHeirarchyWrapper()
    {
        this.children = new List<TaskHeirarchyWrapper>();
    }

} 

但有没有办法序列化这个层次结构而不用编写一个大而丑陋的for循环来组合层次结构中的所有对象?

0 个答案:

没有答案