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.

Use the coupon code LAUNCHDAY for $10 off!

Learn React

7 Comments

LWN

What if I have multiple properties that I may not want to be serialized at run-time ?

Marius Schulz

@LWN: You can create multiple ShouldSerialize{MemberName} methods, one for every property you want to ignore.

Adham

I tried it in ASP.Net Web API oData application, but it didn't work. Any configuration missed?

Luke

@Adham The ODataMediaTypeFormatter does not use Json.NET out of the box like the JsonMediaTypeFormatter does.

Abhishek Jain

This attribute doesn't work, when we have DataMember. Could you suggest?

Islam

Can the ShouldSerialize{MemberName} method have parameters?

LL

Thanks Marius, This was exactly what I needed.