JSON serialization: Ignore selective properties or null properties

Indira Raghavan
2 min readSep 15, 2020

--

Ignore properties or null values when serializing objects to JSON

This article is to explain how to ignore null values or some properties from being serialized to JSON objects for easy transfer of objects between API calls.

Ignore properties from being serialized

Let’s say we have a class with other classes or properties that need not be included during serialization. For eg., Database Id column is a property on the class, but not needed to be serialized JSON object. We can use [JsonIgnore] on the property attribute to ensure this value is not included while serializing the object.

public class TestModelWithJsonAttributes
{
[JsonIgnore]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public string PhoneNumber { get; set; }
}
public void AttributesSerializationTest()
{
var attributesObject = new TestModelWithJsonAttributes()
{
Id = 1,
FirstName = null,
LastName = "Raghavan",
PhoneNumber = "111-111-1111"
};
var json = JsonConvert.SerializeObject(attributesObject);The value for the json: the Id property has been ignored during serilaization.
{
"FirstName": null,
"LastName": "Raghavan",
"PhoneNumber": "111-111-1111"
}

Ignore Null properties

Json Ignore attribute has to be mentioned explicitly for specific properties that gets ignored, and it isn’t dynamic.

Another scenario to consider is some properties may be null, and this does not need to be in the serialized object. Let’s see how to dynamically ignore properties that have null values at the time of serialization:

public class TestModelWithJsonAttributes
{
[JsonIgnore]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public string PhoneNumber { get; set; }
}
public void AttributesSerializationTest()
{
var attributesObject = new TestModelWithJsonAttributes()
{
Id = 1,
FirstName = null,
LastName = "Raghavan",
PhoneNumber = "111-111-1111"
};
var json = JsonConvert.SerializeObject(attributesObject,
Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
The value for the json: the First name has been ignored as well.
{
"LastName": "Raghavan",
"PhoneNumber": "111-111-1111"
}

[JsonIgnore] Attribute is common for both Newtonsoft.Json and System.Text.Json.

To ignore null values there is a slight difference.

  1. For Newtonsoft.Json its JsonSerializerSettings
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};

2. For System.Text.Json it is specified as JsonSerializerOptions

var options = new JsonSerializerOptions
{
IgnoreNullValues = true
};

--

--

Indira Raghavan
Indira Raghavan

No responses yet