6

I want to implement a framework to map JSON string to the calling of C# method. For example, I have a C# class Calculator defined as below.

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

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

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

Is there any 3rd party library to implement this? Or how can I implement it by myself?

4
  • See this Commented Aug 16, 2012 at 12:20
  • Thank you for your quick response. I'm looking at it. Commented Aug 16, 2012 at 12:21
  • 2
    Be careful, someone might send the JSON string {class: System.IO.Directory, method: Delete, parameters: { path: C:\, recursive: true }}... Commented Aug 16, 2012 at 12:23
  • I was not aware of this. Thanks. Commented Aug 16, 2012 at 12:29

1 Answer 1

11

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.