我尝试在下面的示例中使用 Rest.JSON,但我丢失了同名属性父子类(Items)。只需在 Delphi XE 中创建一个新的 vcl 应用程序并粘贴此代码即可查看发生了什么:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Rest.JSON;
type
TParentItemsClass = class
strict private
fID: integer;
fName: string;
public
property ID: integer read fID write fID;
property Name: string read fName write fName;
end;
TParentClass = class
strict private
fID: integer;
fName: string;
fItems: TParentItemsClass;
public
constructor Create;
property ID: integer read FID write fID;
property Name: string read FName write fName;
property Items: TParentItemsClass read FItems write fItems;
end;
TChildItemsClass = class(TParentItemsClass)
strict private
fSomeField: integer;
public
property SomeField: integer read fSomeField write fSomeField;
end;
TChildClass = class(TparentClass)
strict private
fItems: TChildItemsClass;
public
constructor Create;
property Items: TChildItemsClass read fItems write fItems;
end;
TForm1 = class(TForm)
private
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TParentClass }
{ TParentClass }
constructor TParentClass.Create;
begin
fItems:= TParentItemsClass.Create;
end;
{ TChildClass }
constructor TChildClass.Create;
begin
fItems:= TChildItemsClass.Create;
end;
{ TForm1 }
constructor TForm1.Create(AOwner: TComponent);
var AChild, BChild: TChildClass;
begin
inherited;
AChild:= TChildClass.Create;
AChild.Items.ID:= 1;
AChild.Items.SomeField:= 2;
AChild.Items.Name:= 'abc';
BChild:= TJSON.JsonToObject<TChildClass>(TJSON.ObjectToJsonString(AChild));
Application.MessageBox(PWideChar(TJSON.ObjectToJsonString(AChild)+#13+#13+TJSON.ObjectToJsonString(BChild)), '', mb_ok);
end;
end.
这会导致:
一个孩子:
{"items":{"someField":2,"iD":1,"name":"abc"},"iD":0,"name":"","items":null}
B儿童
{"items":null,"iD":0,"name":"","items":null}
如何避免这种情况?我需要 BChild JSON 看起来像 AChild JSON
您的班级
TParentClass
和 TChildClass
都有一个私有字段 fItems
。如果您仔细观察代码输出的 JSON,您已经在问题中发布了答案!
看
AChild
的值:
{
"items": {
"someField": 2,
"iD": 1,
"name": "abc"
},
"iD": 0,
"name": "",
"items": null
}
看看它如何包含两次
items
。这是将 JSON 字符串封送回 BChild
时使用的内容。这肯定不是你想要的。
一个快速的解决方法是将您的内部字段
TChildClass.fItems
重命名为,例如 TChildClass.fItems_
。