Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save arman-hpp/137057680049be36afcee95b7c02af65 to your computer and use it in GitHub Desktop.
Save arman-hpp/137057680049be36afcee95b7c02af65 to your computer and use it in GitHub Desktop.
PropertyIgnoreSerializerContractResolver
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleApp1
{
public class PropertyIgnoreSerializerContractResolver : DefaultContractResolver
{
private readonly HashSet<string> _ignores;
public PropertyIgnoreSerializerContractResolver()
{
_ignores = new HashSet<string>();
}
public void IgnoreProperty(params string[] jsonPropertyNames)
{
foreach (var prop in jsonPropertyNames)
_ignores.Add(prop);
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IsIgnored(property.PropertyName))
{
property.ShouldSerialize = i => false;
property.Ignored = true;
}
return property;
}
private bool IsIgnored(string jsonPropertyName)
{
return _ignores.Contains(jsonPropertyName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment