c# - 如何跳过 Json.Net 中 IEnumerable 类型的默认 JavaScript 数组序列化?

标签 c# json serialization json.net ienumerable

一些实现 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 数组序列化,而只存储类的成员。

我想要的只是我的键和值 - 是否有任何快捷方式可以做到这一点,或者我是否必须实现我自己的自定义序列化程序?

检查 thisthis ,这两个都不是我的问题。已扫描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/

相关文章:

php - mysql查询并编码为json格式

sql - 需要的结果集如下表所示

java - 启用默认输入后,是否有办法覆盖 Jackson 输出的类型?

c# - WCF/REST 日志记录

java - 使用 Maven Replace Plugin 替换 Target/generated-sources 中生成的 Java 文件上的短语

c# - 母版页 HTML Title 标签中 ContentPlaceHolder 的奇怪问题 (MVC2)

php - 关联 PHP 数组(包含对象)的非破坏性 JSON 编码/解码

java - 实现树时使用 java.io.Serializable?

c# - PasswordHasher 方法的用户参数有什么用?

c# - Raspberry Pi 3 - Windows 10 IOT Core 上 C# 中的 USB 到串行通信