.net - 使用 DataContractJsonSerializer 将 ISet<T> 序列化为 JSON

标签 .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 新手,因此我们将不胜感激

最佳答案

看起来这是一个known microsoft bug 。 支持的接口(interface)列表在框架中硬编码,并且 ISet 不是其中之一:

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

是的,错误消息不正确。 因此,DataContractJsonSerializer 无法序列化 ISet 接口(interface),应将其替换为受支持的接口(interface)之一,或者具体的 ISet 实现。

关于.net - 使用 DataContractJsonSerializer 将 ISet<T> 序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6453988/

相关文章:

c# - 服务器端的计时器?

c# - WPF 应用程序的入口点是什么?

java - 嵌套 Json 以使用 Jackson 映射

c# - 用于将 Java 的 JSON 与 C# 相互转换的映射工具

ios - JSON 数据未显示 - 出现错误

Javascript:如何在不知道键名的情况下解析 json 数组?

c# - MEF 不导入根 exe 部分

.net - 如何生成一个与主机名不同的.EXE?

c# - 我应该绑定(bind)到 ICollectionView 还是 ObservableCollection

json - Webpack:加载文件系统中尚不存在的文件