Serializing JSON object for an instance instantiated through a metaclass

*爱你&永不变心* 提交于 2019-12-11 11:52:50

问题


The SuperObject library has a generic method for serializing objects:

type
   TSomeObject = class
   ...
   end;

var
   lJSON       : ISuperObject;
   lContext    : TSuperRttiContext;
   lSomeObject : TSomeObject;
begin
   lSomeObject := TSomeObject.Create;
   lContext := TSuperRttiContext.Create;
   lJSON := lContext.AsJson<TSomeObject>(lSomeObject);

But now I'm dealing with metaclass instances.
This is the object structure:

TJSONStructure = class(TObject);

TReqBase = class(TJSONStructure)
private
   token: Int64;
public
end;

TReqLogin = class(TReqBase)
private
   username,
   password: String;
   module  : Integer;
public
end;


type
   TWebAct = (ttlogin,
              ttsignin);

TReqClass = class of TReqBase;

const
   cWebActStructures: Array[TWebAct] of
   record
      RequestClass : TReqClass;
   end
   = (
      { ttlogin  } (RequestClass: TReqLogin;),
      { ttsignin } (RequestClass: TReqSignIn;)     // Not in definitions above
     ); 

If I now try:

var
   lContext      : TSuperRttiContext;
   lJSON         : ISuperObject;
   lRequestClass : TReqClass;
   lRequestBase  : TReqBase;
begin
   lRequestClass := cWebActStructures[ttlogin].RequestClass;
   lRequestBase := lRequestClass.Create;     // instance of type TReqLogin
   lContext := TSuperRttiContext.Create;
   lJSON := lContext.AsJson<TReqBase>(lRequestBase);

I get the TReqBase serialized: lJSON.AsString = '{"token":-12346789}'
I want to have TReqLogin serialized.
Tried:

  • lContext.AsJson< TReqLogin >(lRequestBase); won't work: incompatible types) [Besides, I would have to list/handle all possible RequestClass types in my routine]

  • lContext.AsJson< lRequestBase.ClassType >(lRequestBase) neither: E2531 Method 'AsJson' requires explicit type argument(s)

Is there any way I can have my lRequestBase serialized as a TReqLogin, TReq... without having to code for them all?


回答1:


The trick is to not create a TSuperRttiContext and call its AsJSOn method myself, but to immediately use:

lJSON := RequestBase.ToJSON;

The ToJSON method will then create a TSuperRttiContext behind the scenes and handle the necessary conversions.

With a big thank you to Marjan for her help.



来源:https://stackoverflow.com/questions/18127452/serializing-json-object-for-an-instance-instantiated-through-a-metaclass

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