Created
December 9, 2020 04:02
-
-
Save arman-hpp/137057680049be36afcee95b7c02af65 to your computer and use it in GitHub Desktop.
PropertyIgnoreSerializerContractResolver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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