Skip to main content

Exclude Property from json during Serialization in newtonsoft

This is a tiny helper class to exclude a property from Json Serialization.

After you add newtonsoft as reference you need to create this class

 

 public class IgnorePropertiesResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
    {
        private readonly HashSet<string> ignoreProps;
        public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
        {
            this.ignoreProps = new HashSet<string>(propNamesToIgnore);
        }
        public IgnorePropertiesResolver()
        {
            this.ignoreProps = new HashSet<string>();
        }
        internal void ignoreProperty(string propName)
        {
            this.ignoreProps.Add(propName);
        }
        internal void ignoreProperties(List<string> ignoredProperties)
        {
            foreach(var prop in ignoredProperties)
            {
                this.ignoreProps.Add(prop);
            }
        }

        protected override Newtonsoft.Json.Serialization.JsonProperty CreateProperty(System.Reflection.MemberInfo member, Newtonsoft.Json.MemberSerialization memberSerialization)
        {
            Newtonsoft.Json.Serialization.JsonProperty property = base.CreateProperty(member, memberSerialization);
            if (this.ignoreProps.Contains(property.PropertyName))
            {
                property.ShouldSerialize = _ => false;
            }
            return property;
        }
    }

 

then you can use this function to use this class

 

var resolver = new IgnorePropertiesResolver();

resolver.ignoreProperty("weight");
resolver.ignoreProperty("sku");

 JsonConvert.SerializeObject(value, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Ignore,
                    ContractResolver = resolver

                });