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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…