Save / load TObject (TPersistent) in XML

all.

I am trying to save my class:

TA= class(TPersistent)
private
    FItems: TObjectList<TB>;

    FOnChanged: TNotifyEvent;
public
    constructor Create;
    destructor Destroy; override;
    ...
    procedure Delete(Index: Integer);
    procedure Clear;
    procedure SaveToFile(const FileName: string);
    ...
    property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
end;

using the following code:

var
  Storage: TJvAppXMLFileStorage;
begin
  Storage := TJvAppXMLFileStorage.Create(nil);
  try
    Storage.WritePersistent('', Self);
    Storage.Xml.SaveToFile(FileName);
  finally
    Storage.Free;
  end;

but the file is always empty.

What am I doing wrong?

+3
source share
2 answers

It seems that TJvCustomAppStorage does not support Generics in properties. The code does not use extended RTTI and calling TJvCustomAppStorage.GetPropCount returns 0.

This leads to another question. Are there Generics-enabled Delphi object serialization libraries? ?

My test code is:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, Generics.Collections, JvAppXmlStorage;
type

  TA = class(TPersistent)
  private
    FItems: TObjectList<TPersistent>;
  public
    constructor Create;
  published
    property
      Items: TObjectList < TPersistent > read FItems write FItems;
  end;

  { TA }

constructor TA.Create;
begin
  FItems := TObjectList<TPersistent>.Create;
end;

var
  Storage: TJvAppXMLFileStorage;
  Test: TA;
begin
  Test := TA.Create;

  Test.Items.Add(TPersistent.Create);

  Storage := TJvAppXMLFileStorage.Create(nil);
  try
    Storage.WritePersistent('', Test);
    WriteLn(Storage.Xml.SaveToString);
    ReadLn;
  finally
    Storage.Free;
  end;

end.
+2
source

I'm not sure, but if TJvAppXMLFileStorage uses RTTI, I think you need to publish the properties you want to save / load.

+1
source

All Articles