1

I'm trying to learn how to serialize objects with Delphi 10.3.3 Rio using this units : REST.JsonReflect and REST.JSON.Types

I wrote this class :

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;

To serialize i do like that :

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;

So my code is working when my class doesn't inherit from any another class, if i declare it like this :

TContainer: class

But when i do like above, with :

TContainer: class(TGraphicControl)

I have a stack overflow exception. I think it's due to inheritance. So my question is, is it possible to skip inherits properties in order that after the serialization, JSONString look like :

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

Thanks

[EDIT] : I find this, with the library Newtonsoft.Json in .NET, a stack overflow user suggest to add this annotation :

[JsonObject(MemberSerialization.OptIn)].

"In a sentence, it will serialize only properties decorated with [JsonProperty] attribute."

But i can't find anything like this with Delphi

  • Please confirm: you want to serialize the members you defined in your class but not those defined in the ancestor class? – fpiette Jan 21 '21 at 12:34
  • yes, that's correct – Damien Lachaume Jan 21 '21 at 13:49
  • Looked in the source code and found nothing to to that. – fpiette Jan 21 '21 at 14:39
  • Since you use local `TJSONMarshal` instance, you could disable marshalling of specific (inherited) fields via its [`RegisterJSONMarshalled`](http://docwiki.embarcadero.com/Libraries/en/REST.JsonReflect.TMarshalUnmarshalBase.RegisterJSONMarshalled) method, e.g.: `m.RegisterJSONMarshalled(TContainer, 'FOwner', False);`. It's going to be a long list of fields to disable inherited from `TGraphicControl`, `TControl` and `TComponent` though. You might as well use RTTI for that purpose. – Peter Wolf Jan 22 '21 at 11:08
  • With that said, it's not a good idea to serialize `TComponent` descendants to JSON. Use data objects instead with binding to UI. `TComponent` and its descendants were designed to stream properly only to DFM. – Peter Wolf Jan 22 '21 at 11:08

0 Answers0