Search code examples
c#jsonserializationjson.net

How to omit obsolete fields while forcing "false" boolean values being present in JSON serialisation?


I'm working with JSON serializer from NewtonSoft.

I have lots of field I would like to omit in the final JSON. In order to do so, I use the following JsonSerializerSettings:

string temp;
JsonSerializerSettings js = new JsonSerializerSettings();
js.DefaultValueHandling = DefaultValueHandling.Ignore;
temp = JsonConvert.SerializeObject(existing_root, Formatting.Indented, js);

This is working fine: all obsolete fields are indeed omitted.

However, I have a boolean field of which I would like to see the value (which is false), but I don't know how to do this. I started as follows:

[JsonProperty("DIAGNOSTICS")]
public bool DIAGNOSTICS { get; set; }

(I find it normal that this gets omitted, seen the settings.)

Then I tried the following in order to force its presence:

[JsonProperty("DIAGNOSTICS")]
public bool DIAGNOSTICS { get; set; } = true;

(I thought, by changing the default value to true, the real value (false) would not be omitted anymore, but I was wrong: the field still gets omitted from the json.)

Does anybody know a way to say to the seraliser:

  • "Don't omit that particular field?", or:
  • "Don't omit boolean values which are false?"

(I would prefer the first solution, if possible)

Thanks in advance


Solution

  • You should just be able to change your JsonProperty attribute to this:

    [JsonProperty("DIAGNOSTICS", DefaultValueHandling = DefaultValueHandling.Populate)]
    

    Try it online