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.


  1. Nicely done, thanks

  2. Hello, this works only for simple objects, when the object contains nested object, those object are ignored
    public ObjectA : BaseA
    public NestedObject nestedObject {get; set;}

Leave a Reply