我想分两步反序列化 JSON-RPC 请求:
第 1 步:将 id
和 method
解析为基类
第 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/