How to serialize Delphi TObjectList<TMyClass> type to XML with TJvAppXMLFileStorage?

假如想象 提交于 2019-12-01 03:45:38

问题


Previously, to save the settings of some applications, I used:

  • A TSettings = class(TPersistent) for the container
  • Each data to serialize in a published property
  • List of object were TCollection and TCollectionItem types
  • The TJvAppXMLFileStorage component to save everything with the single line :

    JvAppXMLFileStorage.WritePersistent(...);

BUT now, I'm using TObjectList as properties in the TSettings class.
So I drop the TCollection/TCollectionItem in favor of Generics ...
When serializing it, there is no list of items ... I think it's because TObjectList is not from TPersistent.

How can I serialize my TObjectList<> with TJvAppXMLFileStorage ?


回答1:


I've successfuly serialize my generic list with few lines of code by calling JvAppXMLFileStorage.WriteList.

First, this is how I serialized the list. The WriteGenericsObjectListItem<TMyClass> method is detailed below.

JvAppXMLFileStorage.WriteList('mylist',TObject(MyGenericList), MyGenericList.Count, WriteGenericsObjectListItem<TMyClass>);

Then, I just need to define how to serialize each item of the generic list. For this, I've created a generic method:

procedure TMySerializer.WriteGenericsObjectListItem<T>(Sender: TJvCustomAppStorage;
  const Path: string; const List: TObject; const Index: Integer; const ItemName: string);
begin
  if(List is TObjectList<T>) then
    if Assigned(TObjectList<T>(List)[Index]) then
      Sender.WritePersistent(Sender.ConcatPaths([Path, Sender.ItemNameIndexPath (ItemName, Index)]), TPersistent(TObjectList<T>(List)[Index]));
end;

That's it!
I haven't modify JCL/JVCL code, only add these to my program.
I think I will submit a patch to JCL/JVCL team to add the compatibility with all Generics containers.

I hope this can help you !



来源:https://stackoverflow.com/questions/12462029/how-to-serialize-delphi-tobjectlisttmyclass-type-to-xml-with-tjvappxmlfilestor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!