How to use SuperObject to invoke methods that uses an Object as parameter in Delphi?
Asked Answered
M

1

9

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

Madelainemadeleine answered 20/10, 2011 at 20:8 Comment(2)
What about to store the LObjectList reference as a private class field or a local variable to the MyMethod ? I know it's a workaround but I can't check what's happening there now.Charily
@Charily - it wouldn't solve my problem. I'd like to send many kinds of objects, because I'm implementing a generic dynamic method invoker. But thanks for the comment, you've been the only one until now.Madelainemadeleine
A
8

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;
Asyllabic answered 6/1, 2012 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.