سؤال

I would like to deserialize a JSON-RPC request in two steps:

Step 1: Parse id and method into a base class
Step 2: Parse params into a second class depending on method

Example:

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;
    }

}

Code (if there were such an object as RawJson)

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

One way to solve it would be if Json.NET has some kind of raw json object, but I can't find one.

So, have I just missed the raw object or is there another good way to do this?


Ps. The id value can be anything: null, string, int, array, etc. It should just be returned in the json-rpc response.

هل كانت مفيدة؟

المحلول

You can use dynamic

dynamic dynJson = JsonConvert.DeserializeObject(s)
if(dynJson.method=="whisper")
{
    var to = dynJson.@params.to; //since params is reserved word
}

This is also possible

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());
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top