Search code examples
c#jsonjson.netpoco

NullValueHandling for properties that are not null but have no data in them


In my POCO object, I have some sub objects that may or may not have some data in them. However, they're declared during object initialization so they're not null.

When I convert them to JSON objects, they show up even if I set the NullValueHandling to Ignore because they're not null.

What's the best way to deal with them so that they don't show up when I serialize my POCO objects to JSON?

Here's an example of a POCO object:

public class Person
{
   [JsonProperty("id")]
   public Guid Id { get; set; }

   [JsonProperty("firstName")]
   public string FirstName { get; set; }

   [JsonProperty("lastName")]
   public string LastName { get; set; }

   [JsonProperty("addresses", NullValueHandling = NullValueHandling.Ignore)]
   public List<Address> Addresses { get; set; } = new List<Address>();
}

In this example, even if I don't have any addresses for this person, when serialized the person class, I see addresses: [] as an empty array.

I really would like to be able to ignore all properties with no data in them. What's the best approach to handle this?


Solution

  • Well the answers seems to be pretty simple : Can Newtonsoft Json.NET skip serializing empty lists?

    If you are permitted to extend the original class then add a ShouldSerializePropertyName function to it. This should return a Boolean indicating whether or not that property should be serialized for the current instance of the class. In your example this might look like this (not tested but you should get the picture):