c# - Json.NET 忽略字典中的空值

标签 c# json.net

使用 JSON.NET 序列化字典时,似乎忽略了 NullValueHandling 设置。

var dict = new Dictionary<string, string>
{
    ["A"] = "Some text",
    ["B"] = null
};

var json = JsonConvert.SerializeObject(dict, Formatting.Indented,
    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });

Console.WriteLine(json);

输出:

{
  "A": "Some text",
  "B": null
}

我预计只有带有键“A”的 KVP 出现在 json 输出中,而 KVP“B”被省略。

如何告诉 Json.NET 只序列化不包含空值的条目?

最佳答案

我只是用 LINQ 从原始字典中过滤掉 null 值并序列化过滤后的字典:

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace JsonSerialize {
    public static class Program {
        private static Dictionary<string, string> dict = new Dictionary<string, string> {
            ["A"] = "Some text",
            ["B"] = null
        };

        public static void Main(string[] args) {
            var filtered = dict
                .Where(p => p.Value != null)
                .ToDictionary(p => p.Key, p => p.Value);

            var json = JsonConvert.SerializeObject(filtered, Formatting.Indented);

            Console.WriteLine (json);
        }
    }
}

给出:

{
  "A": "Some text"
}

关于c# - Json.NET 忽略字典中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53996646/

相关文章:

c# - Azure DevOps 未在发布配置中构建

c# - 从 ViewModel 打开一个窗口

c# - 科学计数法中的 JSON.NET 整数

c# - Newtonsoft JSON.NET 创建类型字典

c# - 通过 Response 发送内存中生成的 .PDF 文件

c# - 在 C# 的 php(pcre) 中找到的分支重置运算符 ("?|"的等价物是什么?

.net - Ubuntu 上 Newtonsoft.Json.Utilities.ConvertUtils 的类型初始值设定项抛出异常

c# - 从 JObject 中提取值

c# - 反序列化真实世界的 JSON 数据

c# - 如何设置 MahApps 窗口网格的样式?