Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?

后端 未结 6 1591
花落未央
花落未央 2020-12-01 00:20

Given a data model:

[DataContract]
public class Parent
{
    [DataMember]
    public IEnumerable Children { get; set; }
}

[DataContract]
publ         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 00:51

    I had the exact same problem and looked up how to build the ContractResolver I was actually looking for and that better answer this question. This only serializes the Properties of the Type T you actually want to serialize, but with this example you can also easily build similar approaches:

    public class TypeOnlyContractResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            property.ShouldSerialize = instance => property.DeclaringType == typeof (T);
            return property;
        }
    }
    

提交回复
热议问题