Reputation: 7278
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.
E.g. 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.
Upvotes: 1
Views: 267
Reputation: 129827
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
Upvotes: 1