Newtonsoft.json: NullValueHandling.Ignore not working as expected with Dictionary

Created on 21 Jan 2016  路  2Comments  路  Source: JamesNK/Newtonsoft.Json

We are serializing Dictionary objects which may or may not have null values and were expecting these to be excluded when serilized with the NullValueHandling.Ignore option. Is this the correct expectation?

See code below for an example.

  var obj1 = new Dictionary<string, string>
  {
    ["a"] = "Value 1",
    ["b"] = null
  };
  var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
  var json = JsonConvert.SerializeObject(obj1, Formatting.Indented, jsonSerializerSettings);
  var obj2 = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  Debug.Assert(obj2.ContainsKey("a"));
  Debug.Assert(!obj2.ContainsKey("b")); // this fails

Most helpful comment

It applies to class properties, not dictionaries.

All 2 comments

It applies to class properties, not dictionaries.

I'd say this is by design.

Still, I am having the same issue. How could one achieve the required functionality? For instance, serializing the following won't get rid of nulls.

new JObject { ["test"] = null }

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dmoeff picture dmoeff  路  17Comments

FrancoisBeaune picture FrancoisBeaune  路  121Comments

Phreak87 picture Phreak87  路  11Comments

Bassman2 picture Bassman2  路  20Comments

danebou picture danebou  路  18Comments