I have the following JSON returning from a Java service
{"Test":{
"value": 1,
"message": "This is a test"
}}
I have the following C# class
class Test {
public int value { get; set; }
public String message { get; set; }
}
However, because the root tag "Test" is returned I cannot directly deserialize this with
Test deserializedTest = JsonConvert.DeserializeObject<Test>(jsonString);
I find I have to wrap the the Test class inside another class for this to work. Is there an easy way to avoid this other than
JToken root = JObject.Parse(jsonString);
JToken testToken = root["Test"];
Test deserializedTest = JsonConvert.DeserializeObject<Test>(testToken.toString());
Finally I have a second question. Most of the services I'm calling can return an Exception object as well. I figured I'd read the "root" tag of the JSON to determine how to deserialize the object. How do I get the first root tag and/or is there a better, more elegant method to handle exceptions from a service?
Thanks
Had the same problem and really wanted to get rid of this 'container', found this solution though you need to use an extra string to find the root object:
// Container I wanted to discard
public class TrackProfileResponse
{
[JsonProperty("response")]
public Response Response { get; set; }
}
// Code for discarding it
var jObject = JObject.Parse(s);
var jToken = jObject["response"];
var response = jToken.ToObject<Response>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With