Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 297
Haruki Avatar asked Oct 20 '11 20:10

Haruki


1 Answers

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;
like image 129
Henri Gourvest Avatar answered Oct 20 '22 22:10

Henri Gourvest