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;