I have a List<ISomething>
in a json file and I can't find an easy way to
deserialize it without using TypeNameHandling.All
(which I don't want / can't use because the JSON files are hand-written).
Is there a way to apply the attribute [JsonConverter(typeof(MyConverter))]
to members
of the list instead to the list?
{
"Size": { "Width": 100, "Height": 50 },
"Shapes": [
{ "Width": 10, "Height": 10 },
{ "Path": "foo.bar" },
{ "Width": 5, "Height": 2.5 },
{ "Width": 4, "Height": 3 },
]
}
In this case, Shapes
is a List<IShape>
where IShape
is an interface with these two implementors:
ShapeRect
and ShapeDxf
.
I've already created a JsonConverter subclass which loads the item as a JObject and then checks which real class to load given the presence or not of the property Path
:
var jsonObject = JObject.Load(reader);
bool isCustom = jsonObject
.Properties()
.Any(x => x.Name == "Path");
IShape sh;
if(isCustom)
{
sh = new ShapeDxf();
}
else
{
sh = new ShapeRect();
}
serializer.Populate(jsonObject.CreateReader(), sh);
return sh;
How can I apply this JsonConverter to a list?
Thanks.
Converts an object to and from JSON. Newtonsoft.Json.
In your class, you can mark your list with a JsonProperty
attribute and specify your converter with the ItemConverterType
parameter:
class Foo
{
public Size Size { get; set; }
[JsonProperty(ItemConverterType = typeof(MyConverter))]
public List<IShape> Shapes { get; set; }
}
Alternatively, you can pass an instance of your converter to JsonConvert.DeserializeObject
, assuming you have implemented CanConvert
such that it returns true when objectType == typeof(IShape)
. Json.Net will then apply the converter to the items of the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With