Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 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 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...