一些实现 IEnumerable 的自定义类型不一定有后备集合。它们可以动态生成,例如使用“yield”或 LINQ。这是一个例子:
public class SOJsonExample
{
public class MyCustomEnumerable : IEnumerable<KeyValuePair<int,float>>
{
public List<int> Keys { get; set; } = new List<int> { 1, 2, 3 };
public List<float> Values { get; set; } = new List<float> { 0.1f, 0.2f, 0.3f };
public IEnumerator<KeyValuePair<int, float>> GetEnumerator()
{
var kvps =
from key in Keys
from value in Values
select new KeyValuePair<int, float>(key, value);
return kvps.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
}
我发现 Json.NET 的默认序列化是枚举每个值并将值存储在 JavaScript 数组中(我不想要)。默认的反序列化器将无法反序列化集合,因为它无法被填充。在这些情况下,我希望 Json.NET 跳过默认的 JavaScript 数组序列化,而只存储类的成员。
我想要的只是我的键和值 - 是否有任何快捷方式可以做到这一点,或者我是否必须实现我自己的自定义序列化程序?
检查 this和 this ,这两个都不是我的问题。已扫描the documentation也一样,但没有找到我要找的东西(也许我找错地方了)。
(编辑#1 - 提高清晰度)
(编辑 #2 - 回答了我自己的问题......见下文)
(编辑 #3 - 更新为更现代的 C#)
最佳答案
回答了我自己的问题 - 请参阅优秀的 documentation on IEnumerable, Lists, and Arrays :
.NET lists (types that inherit from IEnumerable) and .NET arrays are converted to JSON arrays. Because JSON arrays only support a range of values and not properties, any additional properties and fields declared on .NET collections are not serialized. In situations where a JSON array is not wanted the JsonObjectAttribute can be placed on a .NET type that implements IEnumerable to force the type to be serialized as a JSON object instead.
所以,对于我的例子:
[JsonObject]
public class MyCustomEnumerable : IEnumerable<KeyValuePair<int,float>>
{
...
}
关于c# - 如何跳过 Json.Net 中 IEnumerable 类型的默认 JavaScript 数组序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40862408/