2

I have been writing a lot of code lately which involves serialization using Json.NET and due to the nature of the data that I serialize, sometimes not all of their properties need to be serialized so, I do as follows...

public int Foo { get; set; }

public bool ShouldSerializeFoo() => Foo > -1;

This's good and works but involves a lot of work if you have many properties (in my case I have over 100).

So, I wanted to know if there's an alternative to writing those methods.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272

1 Answers1

3

One alternative option is to specific a [DefaultValue(...)] and use the DefaultValueHandling.Ignore feature:

[DefaultValue(-1), JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public int Foo { get; set; } = -1;

Note that it is important to initialize the value to the default value - hence the = -1; in the property initializer.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • But then the OP still has to set a default value for, and apply an attribute to hundreds of properties, which they're trying to prevent. – CodeCaster Jun 11 '18 at 10:09
  • @CodeCaster one way or another, OP is going to have to somehow let the library know which values to ignore, so one way or another there's going to have to be that value per property. Whether the OP thinks this is cleaner is a subjective question for the OP :) But: by the time you have hundreds of properties, maybe codegen is worth a look. – Marc Gravell Jun 11 '18 at 10:11