我想分两步反序列化 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 响应中返回。