2011-06-23 27 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实现。

相关问题