6

Consider the following scenario:

var s1 = "{\"hello\":\"world\", \"test\":\"somevalue\"}";
var s2 = "{\"hello\":\"world\", \"test\":null}";

var j1 = JObject.Parse(s1);
var j2 = JObject.Parse(s2);

j1.Merge(j2, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union, MergeNullValueHandling = MergeNullValueHandling.Merge });

var jf = JsonConvert.SerializeObject(j1, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

The result of jf is {"hello":"world", "test":null}

How would I invoke the library for the result of the merge to be: {"hello":"world"}

Is this a case where i'd have to recursively go through the resultant object and remove null value'd properties manually? Or is there some magic-wand that says "just drop these null values when serializing"

I know about the JsonProperty -> NullValueHandling, but these are dynamic objects I am working with, so the model is unknown.

Johnny
  • 8,939
  • 2
  • 28
  • 33
Andy
  • 12,859
  • 5
  • 41
  • 56
  • 1
    You could remove the null properties from the JObject like that: [dbc's answer.](https://stackoverflow.com/questions/29475467/when-merging-objects-using-newtonsoft-json-how-do-you-ignore-empty-string-value) – Hichame Yessou Feb 17 '18 at 20:19
  • 1
    Also related (and possibly duplicate): [JSON.NET serialize JObject while ignoring null properties](https://stackoverflow.com/q/33027409/3744182) and [Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings](https://stackoverflow.com/q/29258587/3744182). – dbc Feb 17 '18 at 20:31
  • @dbc -- yes, this is what I am looking for. That answers the question if I have to recursively do it. I was hoping there was something already built in, but if this is the only way, then so be it. I appreciate your research. I promise you i looked everywhere for an answer before I posted this! I used the answer from this link you shared: https://stackoverflow.com/questions/33027409/json-net-serialize-jobject-while-ignoring-null-properties – Andy Feb 17 '18 at 21:06
  • 1
    @Andy - Unless you can suppress `null` values when *generating* the `JToken` then recursively pruning them is the only way currently, because `JsonConvert.SerializeObject()` doesn't actually *serialize* a `JToken`. Json.NET treats a `JToken` as something already serialized, and so it simply formats its contents. – dbc Feb 17 '18 at 22:28
  • @dbc -- if you post that as your answer, i will accept. Thanks again for your help. Your solution is going to make a lot of people happy over on my end. ETA: nevermind -- it's marked as dupe. – Andy Feb 17 '18 at 23:25

0 Answers0