2011-06-23 29 views
3

我正在做一些測試,以檢查/理解C#中的.Net類型的JSON序列化。 我正在嘗試使用DataContractJsonSerializer。ISet <T>使用DataContractJsonSerializer序列化爲JSON

這裏是我試圖序列樣本類型:

[DataContract] 
[KnownType(typeof(HashSet<int>))] 
public class TestModel 
{ 
    [DataMember] 
    public string StreetName { get; private set; } 
    [DataMember] 
    public int StreetId { get; private set; } 
    [DataMember] 
    public int NumberOfCars { get; set; } 
    [DataMember] 
    public IDictionary<string, string> HouseDetails { get; set; } 
    [DataMember] 
    public IDictionary<int, string> People { get; set; } 
    [DataMember] 
    public ISet<int> LampPosts { get; set; } 

    public TestModel(int StreetId, string StreetName) 
    { 
     this.StreetName = StreetName; 
     this.StreetId = StreetId; 

     HouseDetails = new Dictionary<string, string>(); 
     People = new Dictionary<int, string>(); 
     LampPosts = new HashSet<int>(); 
    } 

    public void AddHouse(string HouseNumber, string HouseName) 
    { 
     HouseDetails.Add(HouseNumber, HouseName); 
    } 

    public void AddPeople(int PersonNumber, string PersonName) 
    { 
     People.Add(PersonNumber, PersonName); 
    } 

    public void AddLampPost(int LampPostName) 
    { 
     LampPosts.Add(LampPostName); 
    } 
} 

當我再嘗試序列化使用DataContractJsonSerializer,我收到以下錯誤這種類型的對象:

{"'System.Collections.Generic.HashSet`1[System.Int32]' is a collection type and cannot be serialized when assigned to an interface type that does not implement IEnumerable ('System.Collections.Generic.ISet`1[System.Int32]'.)"} 

這味精聽起來不正確。 ISet<T>確實實現了IEnumerable<T>(以及IEnumerable)。 如果我TestModel類,我

public ICollection<int> LampPosts { get; set; }... 

那麼它所有的帆通過更換

public ISet<int> LampPosts { get; set; } 

我是新來的JSON所以任何幫助,將不勝感激

+0

爲什麼你需要'HashSet'或者'ISet'? –

+0

在實際應用中,「LampPosts」將是一個參考類型的集合。 LampPosts不會允許重複,並且很可能會使用NHibernate進行填充。在這種情況下,我相信ISet是一個不錯的選擇。 – rhk98

+0

創建一個模型包裝,爲您做到這一點。 –

回答

2

看起來這是一個known microsoft bug。支持的接口 名單是在框架硬編碼,並且ISet是不是其中之一:

CollectionDataContract.CollectionDataContractCriticalHelper._knownInterfaces = new Type[] 
{ 
    Globals.TypeOfIDictionaryGeneric, 
    Globals.TypeOfIDictionary, 
    Globals.TypeOfIListGeneric, 
    Globals.TypeOfICollectionGeneric, 
    Globals.TypeOfIList, 
    Globals.TypeOfIEnumerableGeneric, 
    Globals.TypeOfICollection, 
    Globals.TypeOfIEnumerable 
}; 

是的,錯誤消息是不正確。 因此,DataContractJsonSerializer無法序列化ISet接口,它應該被替換爲受支持的接口之一或具體的ISet實現。

相關問題