ISet<T> 序列化为 JSON using DataContractJsonSerializer



我正在做一些测试,以检查/理解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的新手,所以如果有任何帮助,我们将不胜感激

看起来这是一个已知的微软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实现替换。

最新更新