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?
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.
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.
Specifies the settings on a JsonSerializer object.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With