I'm importing Json from a file. Let's say it looks like this
{
"name": "Test System",
"devices": [
{
"type": "Touchpanel",
"name": "Main Touchpanel",
"id": "1",
"model": "TS-1070"
},
{
"type": "Display",
"name": "Front Display",
"id": "2",
"hasscreen": false
}
]
}
The class I'm importing to looks like this
class ConfigData
{
[JsonProperty("devices")]
[JsonConverter(typeof(ConfigConverter))]
public IConfig[] Devices { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
ConfigConverter is a custom JsonConverter that checks "type" and figures out what implementation of IConfig the device should be. This works perfectly if I'm only deserializing a single Device, but as soon as I move to an array of devices, the converter gives me an error. Obviously an array of devices is not deserialized the same as a single device.
Is there a native way to say "For each device in this array, use this converter"? Or do I have to make a separate custom converter that handles an array of devices. I'd prefer not to have essentially the same code in multiple customer converters.
The ReadJson in ConfigConverter looks like this
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var config = default(IConfig);
switch (jsonObject["type"].Value<string>().ToLower())
{
case "display":
config = new DisplayConfig();
break;
case "touchpanel":
config = new TouchpanelConfig();
break;
}
serializer.Populate(jsonObject.CreateReader(), config);
return config;
}
This works with a single object and doesn't work with an array. I can envision ways to rewrite it so that it works with an array, but all of those would cause it to stop working with a single object. Looking for the cleanest and most elegant solution that lets me have a single converter that works on both a single object and an array of that object.