sudaid
sudaid

Reputation: 23

How to serialize/deserialize objects using X-SuperObject

Can X-SuperObject serialize / deserialize objects? For example, I have the following structure:

TMyClass
  private
    FField: Integer;
  published
    property field: Integer read FField write FField;
end;

Can I, using X-SuperObject, quickly serialize / deserialize all published-properties of this object, including nested objects? If so, how?

Upvotes: 1

Views: 710

Answers (1)

Randy Sill
Randy Sill

Reputation: 353

Yes, X-SuperObject can serialize/deserialize including nested objects (with some limitations of course). The documentation is light, but their examples cover the basics.

uses
  XSuperJSON, XSuperObject;

type
  TSubClass = class
    A: Integer;
    B: Integer;
  end;

  TMyClass = class
  private
    FField: Integer;
    FSampler: string;
    FSubClass: TSubClass;
  published
    property field: Integer read FField write FField;
    property subClass: TSubClass read FSubClass write FSubClass;
  end;

procedure TForm2.Button3Click(Sender: TObject);
var
  MyClass: TMyClass;
  S: string;
begin
  Memo1.Lines.Clear;

  MyClass := TMyClass.FromJSON('{"field":12}'); //,"subClass":{"A":208,"B":39}}');
  if MyClass.field = 12 then
    Memo1.Lines.Add('MyClass.field has the correct value of 12');
  if Assigned(MyClass.subClass) and (MyClass.subClass.A = 208) then
    Memo1.Lines.Add('MyClass.subClass.A has the correct value of 208');

  S := MyClass.AsJSON;
  Memo1.Lines.Add(S);

  if not Assigned(MyClass.subClass) then
    MyClass.subClass := TSubClass.Create;
  MyClass.subClass.A := 345;
  MyClass.subClass.B := 1024;

  S := MyClass.AsJSON;
  Memo1.Lines.Add(S);
end;

I've also had good success with the stock System.JSON library from Delphi after studying Delphi-JsonToDelphiClass from PKGeorgiev. There are a few attributes to add on occasion to get the results needed, but for the most part it's very capable for stock RTL. https://github.com/PKGeorgiev/Delphi-JsonToDelphiClass

Upvotes: 2

Related Questions