gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:41:28 29 4
gpt4 key购买 nike

我正在做一些测试来检查/理解 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com