Thema: Superobject

Einzelnen Beitrag anzeigen

Benutzerbild von himitsu
himitsu

Registriert seit: 11. Okt 2003
Ort: Elbflorenz
44.184 Beiträge
 
Delphi 12 Athens
 
#3

AW: Superobject

  Alt 9. Okt 2012, 00:50
- '{value: "hello", test: "hello"}' represents a JSON string

- convert JSONString to JSONObject

- convert values of JSONObject to array of TValue

- TRttiMethod.Invoke to call the method

untested code:
Delphi-Quellcode:
uses System.RTTI, Data.DBXJSON, Data.DBXJSONReflect;

type
  TJSONUnMarshal2 = class(TJSONUnMarshal); // hack for protected JSONToTValue

var
  MethodName, ParamStr: string;
  Method: TRttiMethod;
  MethodParams: TArray<TRttiParameter>;
  JSONValues: TJSONValue;
  JSONPair: TJSONPair;
  JSONConvert: TJSONUnMarshal2;
  Values: TArray<TValue>;
  i: Integer;
begin
  MethodName := 'TestMethod';
  ParamStr := '{value: "hello", test: "hello"}'; // '{}' if none Parameters exists

  Method := TRttiContext.Create.GetType(Self.ClassType).GetMethod(MethodName);
  if not Assigned(Method) then
    raise Exception.CreateFmt('Method "%s" does not exists.', [MethodName]);
  MethodParams := Method.GetParameters;

  JSONValues := TJSONObject.ParseJSONValue(ParamStr);
  if not (JSONValues is TJSONObject) then
    raise Exception.CreateFmt('Invalid Parameters for Method "%s".', [MethodName]);
  if TJSONObject(JSONValues).Size <> Length(MethodParams) then
    raise Exception.CreateFmt('Invalid Parameter-Count for Method "%s".', [MethodName]);
  JSONConvert := TJSONUnMarshal2(TJSONConverters.GetJSONUnMarshaler);
  SetLength(Values, TJSONObject(JSONValues).Size);
  for i := 0 to High(Values) do begin
    JSONPair := TJSONObject(JSONValues).Get(i);
    if not SameText(JSONPair.JsonString.Value, MethodParams[i].Name) then
      raise Exception.CreateFmt('Invalid Parameter "%s" for Method "%s".', [MethodParams[i].Name, MethodName]);
    Values[i] := JSONConvert.JSONToTValue(JSONPair.JsonValue, MethodParams[i].ParamType);
  end;

  Result := Method.Invoke(Self, Values).AsString;
end;
$2B or not $2B
  Mit Zitat antworten Zitat