Json.NET忽略字典中的空值

Flo*_*gex 5 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);
Run Code Online (Sandbox Code Playgroud)

输出:

{
  "A": "Some text",
  "B": null
}
Run Code Online (Sandbox Code Playgroud)

我希望json输出中仅包含键为“ A”的KVP,而省略了KVP“ B”。

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

Roa*_*ner 5

我只需null使用 LINQ 从原始字典中过滤出值,然后序列化过滤后的字典:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这使:

{
  "A": "Some text"
}
Run Code Online (Sandbox Code Playgroud)