Jason King Team : Web Development Tags : Web Development Tips & Tricks

Conditional JSON serialisation

Jason King Team : Web Development Tags : Web Development Tips & Tricks

Json.NET is a popular choice for serializing models in .NET. Most developers will have used the [JsonIgnore] attribute to tell Json.NET not to serialize a particular property.   This is great for when you never want to serialize a property but what happens if you won’t know until runtime?

There is a little known way of doing this by creating a new method on your model with the syntax ShouldSerialize[MemberName] which returns a bool.

Consider the following model:

public class TransactionModel
    {
        public decimal Amount { get; set; }
        public string ShortDescription { get; set; }
        public string Description { get; set; }
        public bool ShouldSerializeDescription()
        {
            return SiteSettings.SiteInstanceType != SiteInstanceType.Australia;
        }
    } 

Now the Description property will only be serialized if the current SiteInstanceType is not Australia.   This also means the request will be slightly faster as there is less data to transfer and process by the client.