Search code examples
c#jsonserializationjson.net

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());

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?


Solution

  • If you don't want to create a wrapper type you can use an anonymous type:

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

    If you have more properties, like an exception, it's probably better to create a wrapper type.