2016-12-05 88 views
1

我有一個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 }, 
    ] 
} 

在這種情況下,ShapesList<IShape>其中IShape是與這兩個實施者的接口: ShapeRectShapeDxf

我已經創建了加載項作爲真正的類來加載給出的存在或不存在財產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列表?

謝謝。

+2

['JsonPropertyAttribute.ItemConverterType'](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonPropertyAttribute_ItemConverterType.htm) – kiziu

+0

@kiziu非常感謝!我無法在Google上找到... :( – TesX

回答

1

在你的類,你可以用JsonProperty屬性標記您的列表,並與ItemConverterType參數指定轉換器:

class Foo 
{ 
    public Size Size { get; set; } 

    [JsonProperty(ItemConverterType = typeof(MyConverter))]   
    public List<IShape> Shapes { get; set; } 
} 

或者,你可以通過你的轉換器的一個實例JsonConvert.DeserializeObject,假設你已經實現CanConvert,使其在objectType == typeof(IShape)時返回true。 Json.Net然後將轉換器應用到列表中的項目。

相關問題