Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET Root Tag and Deserialization

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

like image 300
Shaun Avatar asked Sep 04 '11 12:09

Shaun


1 Answers

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>();
like image 135
aybe Avatar answered Oct 12 '22 23:10

aybe