Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

reflection - How to use SuperObject to invoke methods that uses an Object as parameter in Delphi?

We can use the SuperObject library to invoke methods of a certain object by its name and giving its parameters as a json string using the SOInvoker method like in this answer

I'd like to know how do I send a created object as a parameter. I tried to send it like

LObjectList := TObjectList.Create;
LSuperRttiCtx := TSuperRttiContext.Create;
LSuperObjectParameter := LObjectList.ToJson(LSuperRttiCtx);

SOInvoke(MyInstantiatedObject, 'MyMethod', LSuperObjectParameter);

but inside MyMethod the LObjectList reference is lost.

What am I doing wrong?

The superobject library can be downloaded here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It will works if you use array of records intead of object list. If you still want to use object list you will have to write encoders and decoders like this. I have written encoder/decoder for TObjectList, you will have to do the same for your objects and embed the class name somewhere.

ctx.SerialToJson.Add(TypeInfo(TObjectList), ObjectListToJSON);
ctx.SerialFromJson.Add(TypeInfo(TObjectList), JSONToObjectList);

function ObjectListToJSON(ctx: TSuperRttiContext; var value: TValue;
  const index: ISuperObject): ISuperObject;
var
  list: TObjectList;
  i: Integer;
begin
  list := TObjectList(value.AsObject);
  if list <> nil then
  begin
    Result := TSuperObject.Create(stArray);
    for i := 0 to list.Count - 1 do
      Result.AsArray.Add(encodeyourobject(list[i]));
  end else
    Result := nil;
end;

function JSONToObjectList(ctx: TSuperRttiContext; const obj: ISuperObject; var Value: TValue): Boolean;
var
  list: TObjectList;
  i: Integer;
begin
  list := nil;
  case ObjectGetType(obj) of
    stNull:
      begin
        Value := nil;
        Result := True;
      end;
    stArray:
      begin
        list := TObjectList.Create;
        for i := 0 to obj.AsArray.Length - 1 do
          list.Add(decodeyourobject(obj.AsArray[i]));
        Value := list;
        Result := True;
      end;
  else
      result := False;
  end;
end;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...