Json.NET忽略字典中的空值 [英] Json.NET Ignore null values in dictionary

查看:104
本文介绍了Json.NET忽略字典中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When serializing a dictionary with JSON.NET, it seems like the NullValueHandling setting is ignored.

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
}

我希望json输出中仅包含带有键"A"的KVP,而省略了KVP"B".

I expected that only the KVP with key "A" is present in the json output and KVP "B" is omitted.

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

推荐答案

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

I would just filter out the null values from the original dictionary with LINQ and serialize the filtered dictionary:

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);

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

            Console.WriteLine (json);
        }
    }
}

哪个给:

{
  "A": "Some text"
}

这篇关于Json.NET忽略字典中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆