我有一个对象列表,类型为TDepartment,看起来像这样
TDepartment = class
ID : Integer;
Name : string;
ParentDepartmentID : Integer;
end;
我需要创建一个带有部门部门的TJSONObject,所有部门也都可以具有部门部门。因此,其深度是未知的。
我现在正对我来说这根本没有意义,但是我希望生成的JSON看起来像这样:
"department_id": "5",
"department_name": "100",
"parent_dept_id": "",
"subdepartments": [{
"department_id": "8",
"department_name": "300",
"parent_dept_id": "5",
"subdepartments": [{
"department_id": "1",
"department_name": "310",
"parent_dept_id": "8",
"subdepartments": []
请记住,每个级别都有未知数量的兄弟姐妹和孩子。
我想我需要编写一个递归过程,但是我无法可视化它。
最佳答案
首先,您可能希望TDepartment
的声明与您描述的嵌套结构匹配:
TDepartment = class
ID : Integer;
Name : string;
ParentDepartmentID : Integer;
SubDepartments: array of TDepartment;
end;
为了对此进行序列化,我建议使用SuperObject库而不是内置的JSON类:
function TDepartment.Serialize: ISuperObject;
var Context: TSuperRttiContext;
begin
Context := TSuperRttiContext.Create;
try
Result := Context.AsJson<TDepartment>(self);
finally
Context.Free;
end;
end;
OP在评论中提到
TDepartment
包含更多字段,但是只有问题中的字段应该序列化;也必须使用TJSONObject
,并且部门不了解其子级。您可以这样做:function TDepartment.Serialize2(AllDepartments: TList<TDepartment>): TJSONObject;
var Department: TDepartment;
Subdepartments: TJSONArray;
begin
Result := TJSONObject.Create;
Result.AddPair(TJSONPair.Create('department_id', TJSONNumber.Create(ID)));
Result.AddPair(TJSONPair.Create('department_name', Name));
Result.AddPair(TJSONPair.Create('parent_dept_id', TJSONNumber.Create(ParentDepartmentID)));
Subdepartments := TJSonArray.Create;
for Department in AllDepartments do
begin
if (Department.ParentDepartmentID <> ID) then Continue;
Subdepartments.AddElement(Department.Serialize2(AllDepartments));
end;
Result.AddPair(TJSONPair.Create('subdepartments', Subdepartments));
end;