3

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

Dominique
  • 16,450
  • 15
  • 56
  • 112

1 Answers1

4

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

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

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • @Dominique Indeed. I find a lot of documentation to be lacking unless you're doing the general thing, unfortunately. You can see all the configuration options that `JsonProperty` has [here](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonPropertyAttribute.htm). – ProgrammingLlama Jul 26 '21 at 09:22
  • 3
    I also found that `[JsonProperty(nameof(DIAGNOSTICS), DefaultValueHandling = DefaultValueHandling.Include)]` works as well in addition to `.Populate` as you stated. – DekuDesu Jul 26 '21 at 09:31
  • 1
    @DekuDesu The difference between those two is in deserializing: `Populate` will also set the property when deserializing, `Include` will not – Charlieface Jul 26 '21 at 10:20
  • @Charlieface, you're absolutely correct, however, in this particular use case his auto property will always have a default value assigned when the type(bool) is initialized by the CLR since it's a boolean. – DekuDesu Jul 26 '21 at 10:34