JSON deserialization with JSON.net: class hierarchies


In part 1 of this series I described the basics of creating classes from a JSON string and then simply deserializing the string into a (list of) classes. That way, you don’t have all the hooplah of SOAP, but still have strongly-typed classes in your client app. But beware, there is no formal contract either, so on a beautiful morning you might start to think that either you had too much of a drink yesterday evening, or that the company providing the data feed for your app indeed has started to sell Windows Phone 7 devices made by Sony, with a 65” screen.
Looking at the JSON string you now see something like this:
[
{
"Brand": "Nokia","Type" : "Lumia 800", "Device" : "Phone",
"Specs":{"Storage" : "16GB", "Memory": "512MB","Screensize" : "3.7"}
},
{
"Brand": "Sony", "Type" : "KDL-65HX920","Device" : "TV",
"Specs":{"Screensize" : "65", "FullHD" : "Yes", "ThreeD" : "Yes" }
},
{ "Brand": "Nokia","Type" : "Lumia 900","Device" : "Phone",
"Specs":{"Storage" : "8GB", "Memory": "512MB","Screensize" : "4.3" }
},
{
"Brand": "Samsung", "Type" : "UE55C9000","Device" : "TV",
"Specs":{"Screensize" : "55", "FullHD" : "Yes", "ThreeD" : "Yes" }
},
]None of the two options mentioned before appear to be true: apparently the company has diversified: they are now selling TV's as well. Of course you could run this trough json2csharp, which will give you this:public class Specs
{
public string Storage { get; set; }
public string Memory { get; set; }
public string Screensize { get; set; }
public string FullHD { get; set; }
public string ThreeD { get; set; }
}
public class RootObject
{
public string Brand { get; set; }
public string Type { get; set; }
public string Device { get; set; }
public Specs Specs { get; set; }
}
This will work, but not for the purpose of what I’d like to show. We refactor the whole stuff into an object structure like this:

Or, in code (put into one file)
namespace JsonDemo
{
public abstract class Device
{
public string Brand { get; set; }
public string Type { get; set; }
}
public class Phone : Device
{
public PhoneSpecs Specs { get; set; }
}
public class Tv : Device
{
public TvSpecs Specs { get; set; }
}
public abstract class Specs
{
public string Screensize { get; set; }
}
public class PhoneSpecs : Specs
{
public string Storage { get; set; }
public string Memory { get; set; }
}
public class TvSpecs: Specs
{
public string FullHd { get; set; }
public string ThreeD { get; set; }
}
}
If you think this is a ludicrous complicated way to store such a simple data structure I think you are quite right, but a) they don’t call me a Senior So