You can do this by creating a custom DefaultContractResolver and overriding its CreateProperty method.
For example, given the base Foo and the derivative Bar :
public class Foo { [JsonIgnore] public string Name { get; set; } public int Age { get; set; } } public class Bar : Foo { }
You can create the following contract resolver:
public class MyTypeContractResolver<T> : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); property.Ignored = false; property.ShouldSerialize = propInstance => property.DeclaringType != typeof (T); return property; } }
This sets all the properties of Ignored = false , and then analyzes them according to the given predicate:
propInstance => property.DeclaringType != typeof (T);
Which in our case means "you should serialize only if they are not of type Foo " (because Foo is DeclaryingType ).
And then, when you want to deserialize, you pass the contract recognizer instance to JsonSerializerSettings :
var bar = new Bar(); var result = JsonConvert.SerializeObject(bar, new JsonSerializerSettings {ContractResolver = new MyTypeContractResolver<Bar>()});
Yuval Itzchakov
source share