How to exclude property from Json Serialization

后端 未结 7 1389
粉色の甜心
粉色の甜心 2020-11-22 13:22

I have a DTO class which I Serialize

Json.Serialize(MyClass)

How can I exclude a public property of it?

(It has to

相关标签:
7条回答
  • 2020-11-22 13:52

    Sorry I decided to write another answer since none of the other answers are copy-pasteable enough.

    If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, etc. etc. here's how you do it in Newtonsoft.Json

    //short helper class to ignore some properties from serialization
    public class IgnorePropertiesResolver : DefaultContractResolver
    {
        private readonly HashSet<string> ignoreProps;
        public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
        {
            this.ignoreProps = new HashSet<string>(propNamesToIgnore);
        }
    
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            if (this.ignoreProps.Contains(property.PropertyName))
            {
                property.ShouldSerialize = _ => false;
            }
            return property;
        }
    }
    

    Usage

    JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
            { ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) };);
    

    Note: make sure you cache the ContractResolver object if you decide to use this answer, otherwise performance may suffer.

    I've published the code here in case anyone wants to add anything

    https://github.com/jitbit/JsonIgnoreProps

    0 讨论(0)
提交回复
热议问题