Root tag and JSON.NET 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, since the root tag "Test" is returned, I cannot directly deserialize this with

 Test deserializedTest = JsonConvert.DeserializeObject<Test>(jsonString); 

I believe that for this you need to wrap the Test class inside another class. 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 services that I call can also return an Exception object. I decided that I would read the โ€œrootโ€ JSON tag to determine how to deserialize the object. How to get the first root tag and / or is there a better, more elegant way to handle exceptions from a service?

thanks

+7
source share
4 answers

If you do not want to create a shell type, you can use an anonymous type:

 var test = JsonConvert.DeserializeAnonymousType(response.Content, new { Test = new Test()}).Test; 

If you have more properties, such as an exception, it is probably best to create a shell type.

+1
source

The answer is actually an object containing a Test object. Therefore, your object model should look the same. And since the answer may contain an exception, you should also reflect this:

 class Response { public Test Test { get; set; } public JObject Exception { get; set; } } 

It is assumed that you do not know what Exception looks like. If you do, use a specific type instead of a JObject . You can then handle the Response object based on Exception null .

+2
source

Had the same problem and really wanted to get rid of this โ€œcontainerโ€, found this solution, although you need to use an extra line 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>(); 
+2
source

Just write a wrapper:

 public class Wrapper { public Test Test { get; set; } } 

and then deserialize this wrapper and retrieve the Test instance via the Test property:

 Test deserializedTest = JsonConvert.DeserializeObject<Wrapper>(jsonString).Test; 
+1
source

All Articles