I'm trying to deserialize different object types inside a json array in the most efficient way possible but I can't really see how this can be done in any sort of straightforward way. I'm using the Newtonsoft.Json library for parsing.
I have set up a simple example to illustrate the problem I'm trying to solve, the classes I wish to bind to and the JSON format I'm working with is defined below:
class Car
{
public int Wheels { get; set; }
public String Manufacturer { get; set; }
public String Colour { get; set; }
public double EngineSize { get; set; }
public String Year { get; set; }
}
class Aeroplane
{
public String Model { get; set; }
public String Airline { get; set; }
public int JourneyCount { get; set; }
}
class Ship
{
public String Name { get; set; }
public String Company { get; set; }
public int Capacity { get; set; }
public String YearBuilt { get; set; }
}
And here's the JSON I'm trying to bind to these classes. It's set up as an array with three different nested object types at each position. Basically each element/index in the array contains three objects, namely a car, aeroplane and ship.
{[
{
"car": {
"wheels": 4,
"manufacturer": BMW,
"colour": "Black",
"engineSize": "1.6"
},
"aeroplane": null,
"ship": null
},
{
"car": {
"wheels": 4,
"manufacturer": BMW,
"colour": "Black",
"engineSize": "1.6"
},
"aeroplane": {
"model": "Dreamliner",
"airline": "Emirates",
"journeyCount": 4798
},
"ship": {
"name":"Queen Mary",
"company":"Cunard",
"capacity": 890,
"yearBuilt": 2000
}
},
{
"car": {
"wheels": 4,
"manufacturer": BMW,
"colour": "Black",
"engineSize": "1.6"
},
"aeroplane": {
"model": "Boeing 777",
"airline": "BA",
"journeyCount": 6158
},
"ship": {
"name":"HMS Diamond",
"company":"Royal Navy",
"capacity": 500,
"yearBuilt": 2010
}
}
]}