Memetisch

Dein Weltmodell ist deine Realität

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> : 
        DefaultContractResolver
{
  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;
}

2 thoughts on “Json.NET and Serializing only base class properties

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

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Back to top