我试图在下面的例子中使用Rest.JSON,但我丢失了相同的名称属性parent-child class(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}
BChild
{"items":null,"iD":0,"name":"","items":null}
如何避免这一点?我需要BChild JSON看起来像AChild JSON
1条答案
按热度按时间pw9qyyiw1#
类
TParentClass
和TChildClass
都有一个私有字段fItems
。如果你仔细观察你的代码输出的JSON,你已经在你的问题中给出了答案!看看
AChild
的值:看看它如何包含
items
两次。这就是当你将JSON字符串封送回BChild
时所使用的。这肯定不是你想要的一个快速的解决方法是将内部字段重命名为
TChildClass.fItems
,例如TChildClass.fItems_
。