- by Tim
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; }
Nicely done, thanks
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;}
}