如何JSON字符串映射到C#方法的调用 [英] How to map JSON string to the calling of C# method
问题描述
我想实现一个框架,以JSON字符串映射到C#方法的调用。例如,我有一个C#类计算器定义如下:
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);
}
有如下JSON字符串。当框架接收这个字符串,它创建类计算器/新的对象。然后调用它的功能添加。并通过价值12和43的功能参数。
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?
推荐答案
一个小型的工作样本。当然,许多支票丢失。 (使用 Json.Net )
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;
}
}
这篇关于如何JSON字符串映射到C#方法的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!