gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:04:59 26 4
gpt4 key购买 nike

使用 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/

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