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

后端 未结 6 1599
花落未央
花落未央 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:56

    Having encountered a similar problem, this is the ContractResolver I came up with:

    public class StrictTypeContractResolver : DefaultContractResolver
    {
        private readonly Type _targetType;
    
        public StrictTypeContractResolver( Type targetType ) => _targetType = targetType;
    
        protected override IList CreateProperties( Type type, MemberSerialization memberSerialization )
            => base.CreateProperties
            (
                _targetType.IsAssignableFrom( type ) ? _targetType : type,
                memberSerialization
            );
    }
    

    It cuts off only the properties of targetType's descendants, without affecting the properties of its base classes or of other types that targetType's properties might reference. Which, depending on your needs, may or may not be an improvement over the other answers provided here at the time.

提交回复
热议问题