【发布时间】:2017-12-15 15:52:19
【问题描述】:
TDictionary : SaveToFile / LoadFromFile
多么优雅的解决方案! 首先,一切都按预期运行。
内容以看起来正确的 JSON 格式保存到文件中。 但是重新加载文件后,出现了问题:
Type
TEnumCategTypes = ( e_SQL1, e_VBA, e_Text );
TCategParams = class
fontStyles : TFontStyles;
rgbColor : COLORREF;
end;
TdictCategory = class ( TDictionary<TEnumCategTypes, TCategParams> )
public
public class function LoadFromFile( const AFileName: string ): TdictCategory;
public class procedure SaveToFile( const AFileName: string; dict: TdictCategory );
end;
implementation
class procedure TdictCategory.SaveToFile( const AFileName: string; dict: TdictCategory );
var
stream : TStringStream;
begin
try
stream := TStringStream.Create( TJson.ObjectToJsonString( dict ) ) ;
stream.SaveToFile( AFileName )
finally
stream.Free;
end;
end;
//---
class function TdictCategory.LoadFromFile( const AFileName: string ): TdictCategory;
var
stream: TStringStream;
begin
stream := TStringStream.Create;
try
stream.LoadFromFile( AFileName );
result := TJson.JsonToObject<TdictCategory>( stream.DataString );
finally
stream.Free;
end;
end;
测试如下。所有的荣耀都结束了。 这是代码,包括注释:
..
var
cc: Colorref;
begin
.. // fill values
cc := DictCategory.Items[ e_SQL1 ].rgbColor; // Okay, it works
TdictCategory.SaveToFile( 'category.json', DictCategory ); // Even the contents of the file, looks good
DictCategory.Clear;
DictCategory.Free;
DictCategory := nil;
DictCategory := TdictCategory.LoadFromFile( 'category.json' ); // DictCategory is no longer NIL, and it looks optically well..
cc := DictCategory.Items[ e2_sql_aggregate ].rgbColor; // C R A S H !!! with AV
看来Delphi(Berlin 10.1),不能序列化Dictionary!如果这是真的,那真的让我很伤心。我相信还有很多其他的。还是附上的代码有错误?
【问题讨论】:
-
你的问题很冗长。归结为
TJson.JsonToObject<T>(..)(也可能是TJson.ObjectToJsonObject<T>(..))不能与TList<T>或TDictionary<T>等泛型类一起正常工作。
标签: delphi serialization tdictionary