Json.NET and Serializing only base class properties

I was just working with Json.NET in C# and was looking for a solution to create a JSON-String from an object where I only wanted to put in the properties of the base type, as I have stored subtypes in memory which contain additional ViewModel properties that were unneeded as I only needed the business data. As I didn’t find anything fitting via Google, I researched how to build a custom ContractResolver that only serializes the Properties belonging to my business model class type T:

public class DerivedTypeFilterContractResolver<T> : 
  protected override JsonProperty CreateProperty(
        MemberInfo member, 
        MemberSerialization memberSerialization)
    JsonProperty property = base.CreateProperty(
         member, memberSerialization);
    if (property.DeclaringType == typeof(T))
        property.ShouldSerialize =
          instance => false;
    return property;
, Posted Thursday, May 2nd, 2013 under Programming.

One comment so far

  1. Nicely done, thanks

Leave a Reply