首页 > 解决方案 > Delphi - 对象的序列化:忽略继承的属性

问题描述

我正在尝试学习如何使用以下单元使用 Delphi 10.3.3 Rio 序列化对象:REST.JsonReflect 和 REST.JSON.Types

我写了这门课:

TContainer: class(TGraphicControl)
private
  [JSONMarshalledAttribute(False)] // Test to hide a property : works
  FObj: TObject;
  FId: Integer;
  FContainerName: string;
  [JsonName('Type')] // Test to customize the property name : works
  FContainerType: string;
public
  property Id: Integer read FId write FId;
  property ContainerName: string read FContainerName write FContainerName;
  property ContainerType: string read FContainerType write FContainerType;
end;

要序列化我这样做:

var
  m: TJSONMarshal;  
  JSONString: String;
  Container: TContainer;
begin
  Container:= TContainer.Create(nil);
  Container.FId := 12;
  Container.FContainerName := 'Container001';
  Container.FContainerType := 'TYPE_005';

  JSONString := m.Marshal(Container).Format;

所以当我的类没有从任何其他类继承时,我的代码正在工作,如果我这样声明它:

TContainer: class

但是当我喜欢上面的时候,用:

TContainer: class(TGraphicControl)

我有一个堆栈溢出异常。我认为这是由于继承。所以我的问题是,是否可以跳过继承属性以便在序列化之后 JSONString 看起来像:

{
    "id": 7,
    "containerName": "Container001",
    "Type": "TYPE_005"
}

谢谢

[编辑]:我发现这个,使用 .NET 中的库 Newtonsoft.Json,堆栈溢出用户建议添加此注释:

[JsonObject(MemberSerialization.OptIn)].

“一句话,它只会序列化用 [JsonProperty] 属性修饰的属性。”

但我在德尔福找不到这样的东西

标签: jsonobjectdelphiserializationdelphi-10.3-rio

解决方案


推荐阅读