Delphi通用的序列化代码

type
  TFoo = class
  public
    function Object2Json<T>(o: T): string;
    function Json2Object<T>(j: string): T;
  end;
  
implementation

function TFoo.Json2Object<T>(j: string): T;
var
  ctx: TSuperRttiContext;
begin
  ctx := TSuperRttiContext.Create;
  try
    Result := ctx.AsType<T>(SO[j]);
  finally
    ctx.Free;
  end;
end;

function TFoo.Object2Json<T>(o: T): string;
var
  ctx: TSuperRttiContext;
  obj: ISuperObject;
begin
  ctx := TSuperRttiContext.Create;
  try
    obj := ctx.AsJson<T>(o);
    Result := obj.AsString;
  finally
    ctx.Free;
  end;
end;

使用了SuperObject,需要编译器支持泛型特性,老版本的似乎只能是望梅止渴了

原文地址:https://www.cnblogs.com/littlestone08/p/2917439.html