使用DataContractJsonSerializer </t> ISet <t>序列化为JSON

时间:2011-06-23 12:28:32

标签: .net json

我正在做一些测试来检查/理解C#中的.Net类型的JSON序列化。 我正在尝试使用DataContractJsonSerializer。

以下是我尝试序列化的示例类型:

[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 ISet<int> LampPosts { get; set; }

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

然后它全部通过。

我是JSON的新手,所以非常感谢任何帮助

1 个答案:

答案 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实现。

相关问题