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

前端 未结 1 1998
自闭症患者
自闭症患者 2020-12-16 19:44

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 answe

相关标签:
1条回答
  • 2020-12-16 20:40

    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;
    
    0 讨论(0)
提交回复
热议问题