Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET Ignore null values in dictionary

Tags:

c#

json.net

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

Output:

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

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

How can I tell Json.NET to only serialize the entries that do not contain null values?

like image 826
Flogex Avatar asked Jan 01 '19 15:01

Flogex


People also ask

How do I ignore JSON property if null?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

What is NullValueHandling?

This sample serializes an object to JSON with NullValueHandling set to Ignore so that properties with a default value aren't included in the JSON result.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

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

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

            Console.WriteLine (json);
        }
    }
}

Which gives:

{
  "A": "Some text"
}
like image 113
RoadRunner Avatar answered Sep 30 '22 12:09

RoadRunner