c# - Json.NET 中的 RawJSON 对象

标签 c# json.net json-rpc

我想分两步反序列化 JSON-RPC 请求:

第 1 步:idmethod 解析为基类
第 2 步: 根据方法将 params 解析为第二个类

示例:

interface IAction
{
    bool Exec();
}

class Request
{
    [JsonProperty("method")]
    public string Method;

    [JsonProperty("params")]
    public RawJson Params;

    [JsonProperty("id")]
    public RawJson Id;
}

class Whisper : IAction
{
    [JsonProperty("to")]
    public string To;

    [JsonProperty("msg")]
    public string Message;

    public bool Exec()
    {
        // Perform the whisper action
        return true;
    }
}

class Say : IAction
{
    [JsonProperty("msg")]
    public string Message;

    public bool Exec()
    {
        // Perform the say action
        return true;
    }

}

代码(如果存在RawJson这样的对象)

Request req = JsonConvert.DeserializeObject<Request>(s);
if( req.Method == "whisper" )
{
    Whisper whisper = RawJson.DeserializeObject<Whisper>();
    whisper.Exec();
}

解决这个问题的一种方法是 Json.NET 有某种原始 json 对象,但我找不到。

那么,我是否错过了原始对象,或者还有其他好方法来做到这一点?


诗。 id 值可以是任何值:null、string、int、array 等。它应该在 json-rpc 响应中返回。

最佳答案

您可以使用动态

dynamic dynJson = JsonConvert.DeserializeObject(s)
if(dynJson.method=="whisper")
{
    var to = <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a6e736440796564244a7a6b786b6779247e65" rel="noreferrer noopener nofollow">[email protected]</a>; //since params is reserved word
}

这也是可以的

string json = "{method:'whisper',params:{to:'aaa',msg:'msg1'}}";

var jObj = JsonConvert.DeserializeObject(json) as JObject;
if (jObj["method"].ToString() == "whisper")
{
    var whisper = JsonConvert.DeserializeObject<Whisper>(jObj["params"].ToString());
}

关于c# - Json.NET 中的 RawJSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718638/

相关文章:

c# - Msmq .NET api MessageQueue.Send 不会在预期的地方抛出

c# - WP7 中的加速度计问题

C# 如何很好地将 float 格式化为没有不必要的小数点 0 的字符串?

c# - 如何让 Json.NET 将空 XML 元素序列化为空字符串

java - 应用程序在 Spring Boot 3.0.0 新版本中运行失败

go - 解码为接口(interface)类型

c# - setter/getter 中的空合并运算符

c# - 如何让 Newtonsoft 按原样反序列化日期并将其命名为 utc?

c# - Json.NET Uri(反)序列化错误

types - golang中的json-rpc,id为字符串