简体   繁体   English

JSON反序列化。

[英]JSON deserialization.

I have a simple WCF RESTful service with only one operation which has string as a parameter void Process(string item) . 我有一个简单的WCF RESTful服务,只有一个操作,该操作具有将string作为参数void Process(string item) The item is a JSON serialized object and it could be anything. item是JSON序列化的对象,可以是任何东西。

In this particular case about 20 different classes could be sent to this service. 在这种特殊情况下,可以将大约20个不同的类发送到此服务。 What is the proper and handy way to deserialize those objects? 反序列化这些对象的正确便捷方法是什么? How do i know know what's actually behind the JSON? 我怎么知道JSON背后到底是什么? I could include some Type field and do something like using Json.NET: 我可以包括一些Type字段,并使用Json.NET做一些事情:

dynamic json = JsonConvert.DeserializeObject(input);

, examine json.Type and then deserialize input string with JsonConvert.DeserializeObject<T>() , but I am not sure that this is a good idea. ,检查json.Type ,然后使用JsonConvert.DeserializeObject<T>()反序列化输入字符串,但是我不确定这是一个好主意。 Do you have any ideas? 你有什么想法?

Although I would use WCF with many OperationContract methods as mentioned in comments, a dynamic way is also possible. 尽管如注释中所述,我将WCF与许多OperationContract方法一起使用,但是也可以采用动态方式。 Don't forget, many checks are omitted, and there is a lot of room to improve. 别忘了,很多检查都被省略了,还有很多改进的余地。 Just consider it as POC work. 只需将其视为POC工作即可。

Suppose you have a server object to execute methods on. 假设您有一个服务器对象可以在其上执行方法。

public class ServerClass1
{
    public int Add(int i,int j)
    {
        return i + j; 
    }

    public string Hello()
    {
        return "HELLO";
    }
}

and you received these jsons somehow and execute dynamically 并且您以某种方式收到了这些json并动态执行

req1 : {"method":"Add","parameters":[3,5]} req1: {"method":"Add","parameters":[3,5]}

var res1 = Exec(req1, new ServerClass1());

req 2: {"method":"Hello","parameters":null} 需求2: {"method":"Hello","parameters":null}

var res2 = Exec(req2, new ServerClass1());

Helper methods/classes 辅助方法/类

public class Request
{
    public string method;
    public object[] parameters;
}

public static object Exec(string json, object target)
{
    var req = JsonConvert.DeserializeObject<Request>(json);

    var method = target.GetType().GetMethod(req.method, BindingFlags.Public | BindingFlags.Instance);
    if (method == null) throw new InvalidOperationException();

    object[] parameters = new object[0];
    if (req.parameters != null)
    {
        parameters = method.GetParameters().Zip(req.parameters, (m, p) => Convert.ChangeType(p, m.ParameterType)).ToArray();
    }

    return method.Invoke(target, parameters);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM