简体   繁体   中英

Deserialize JSON object into a class with a "dynamic" property

I am receiving JSON messages that are matched to the following class:

public class Response
{
    public int Code { get; }
    public string Message { get; }
    public string Result { get; }
}

But the value of Result property depends on what we get in Code and does not have a fixed structure.

Eg if Code = 1 , Result will return a list of objects of type X and if Code = 2 , Result will return a list of objects of type Y.

When I try to deserialize a message I am receiving, having Result type set to string does not seem to work.

var responseObj = JsonConvert.DeserializeObject<Response>(response);
if (responseObj.Code == 1)
{
    return responseObj.Result;
}

The return statement above throws the following exception:

Unexpected character encountered while parsing value: [. Path 'Result'

How can I define my class so that it receives the entire text of Result and I can decide about its deserialization later? Because all my requests respond to with the above structure and I'd like to manage all these requests from the same place.

How can I define my class so that it receives the entire text of Result and I can decide about its deserialization later?

If that is what you want to do then make your Result property a JToken instead of a string as shown below. You will also need to add setters to all of the properties shown in your Response class to allow the deserialization to work properly: you can't deserialize into read-only properties.

public class Response
{
    public int Code { get; set; }
    public string Message { get; set; }
    public JToken Result { get; set; }
}

Once you know what type the Result should be converted into, you can use the ToObject() method to do that. For example:

Response responseObj = JsonConvert.DeserializeObject<Response>(response);

if (responseObj.Code == 1)
{
    var listOfX = responseObj.Result.ToObject<List<X>>();
    ...
}

Fiddle: https://dotnetfiddle.net/pz5m63

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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