Marius Schulz
Marius Schulz
Front End Engineer

Conditionally Serializing Fields and Properties with Json.NET

In this post, I want to show you two ways to opt out of serialization for a particular object field or property.

#Ignoring Fields and Properties During Serialization

When you are serializing an object using Json.NET, all its public fields and properties will be serialized by default.

If you want to exclude certain members from serialization, you can place the JsonIgnoreAttribute on them:

public class BlogPost
{
    public string Title { get; set; }

    [JsonIgnore]
    public DateTime LastModified { get; set; }
}

In the above example, [JsonIgnore] causes the LastModified property to be ignored during serialization. As far as the serialization process is concerned, the property simply doesn't exist, if you will. LastModified will thus never be serialized (nor deserialized, respectively).

Sometimes, however, you might need to decide at runtime whether or not to serialize a particular field or property. [JsonIgnore] won't be of any help in that case because the attribute prevents the decorated object member from being serialized under any circumstance.

Luckily, Json.NET offers a way to serialize object members depending on some condition.

#Conditionally Serializing Object Members

There's a little known feature of Json.NET that lets you determine at runtime whether or not to serialize a particular object member: On the object you're serializing, you have to define a public method named ShouldSerialize{MemberName} returning a boolean value.

Json.NET will call that method during serialization to determine whether or not to serialize the corresponding object member. If your method returns true, the member will be serialized; otherwise, it won't.

It's totally up to you how you make the decision whether to return true or false. In the end, it's just a regular method returning a boolean value.

#Full Disclosure: The Caveats

Keep in mind that {MemberName} has to exactly match the name of the object member you want to ignore, character by character. If you refactor the member's name, make sure to adjust the ShouldSerialize{MemberName} method as well or it'll stop working.