How to map JSON string to C # method call

I want to implement a structure to map a JSON string to a call to a C # method. For example, I have a C # class calculator as shown below.

// C# class
class Calculator
{
public:
    int add (int x, int y);
    int sub (int x, int y);
}

There is a JSON string as shown below. When the framework receives this line, it creates / a new object of the class Calculator. Then call its add function. And pass the values ​​12 and 43 to the function as parameters.

// JSON string
"{
\"class\":\"Calculator\",
\"method\":\"add\",
\"parameters\": {
    \"x\" : \"12\", \"y\" : \"43\"
    }
}"

Is there a third-party library to implement this? Or how can I implement it myself?

+5
source share
1 answer

A small working sample. Of course, many checks are missing. (Using Json.Net )

string jsonstring = "{\"class\":\"Calculator\",\"method\":\"add\",\"parameters\": { \"x\" : \"12\", \"y\" : \"43\" }}";

var json = (JObject)JsonConvert.DeserializeObject(jsonstring);

Type type = Assembly.GetExecutingAssembly()
                    .GetTypes()
                    .First(t => t.Name==(string)json["class"]);

object inst = Activator.CreateInstance(type);
var method =  type.GetMethod((string)json["method"]);
var parameters = method.GetParameters()
        .Select(p => Convert.ChangeType((string)json["parameters"][p.Name], p.ParameterType))
        .ToArray();
var result =  method.Invoke(inst, parameters);

var toReturn = JsonConvert.SerializeObject(new {status="OK",result=result });

-

class Calculator
{
    public int add(int x, int y)
    {
        return x + y;
    }
}
+9
source

All Articles