我有一個List<ISomething>
在json文件中,我無法找到一個簡單的方法來 反序列化它,而不使用TypeNameHandling.All
(我不想/不能使用,因爲JSON文件是手寫的)。使用自定義JsonConverter反序列化接口列表?
有沒有辦法將屬性[JsonConverter(typeof(MyConverter))]
應用到列表的成員 而不是列表?
{
"Size": { "Width": 100, "Height": 50 },
"Shapes": [
{ "Width": 10, "Height": 10 },
{ "Path": "foo.bar" },
{ "Width": 5, "Height": 2.5 },
{ "Width": 4, "Height": 3 },
]
}
在這種情況下,Shapes
是List<IShape>
其中IShape
是與這兩個實施者的接口: ShapeRect
和ShapeDxf
。
我已經創建了加載項作爲真正的類來加載給出的存在或不存在財產Path
一個JObject,然後檢查一個JsonConverter子類:
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;
如何申請這個JsonConverter列表?
謝謝。
['JsonPropertyAttribute.ItemConverterType'](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonPropertyAttribute_ItemConverterType.htm) – kiziu
@kiziu非常感謝!我無法在Google上找到... :( – TesX