Last active
November 5, 2018 13:25
-
-
Save chrisfcarroll/50fe9a235f388e285a05af8c31852b08 to your computer and use it in GitHub Desktop.
ContractResolvers for Newtonsoft.Json which can ignore fields either by predicate or by name
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; | |
using System.Reflection; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
public class DeSerializeExcludingFieldsContractResolver : DefaultContractResolver | |
{ | |
readonly Type type; | |
readonly Predicate<JsonProperty> ignoreProperty; | |
public DeSerializeExcludingFieldsContractResolver(Type type, Predicate<JsonProperty> ignoreProperty) | |
{ | |
this.type = type; | |
this.ignoreProperty = ignoreProperty; | |
} | |
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) | |
{ | |
JsonProperty property = base.CreateProperty(member, memberSerialization); | |
property.Ignored = property.DeclaringType == type && ignoreProperty(property); | |
return property; | |
} | |
} |
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.Linq; | |
using System.Reflection; | |
using System.Text.RegularExpressions; | |
using System.Web; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
public class IgnoreByNameContractResolver : DefaultContractResolver | |
{ | |
readonly IEnumerable<Regex> ignores; | |
public IgnoreByNameContractResolver(params string[] typeNameOrPropertyNameRegexesToIgnore) | |
{ | |
ignores = typeNameOrPropertyNameRegexesToIgnore.Select(p => new Regex(p)); | |
} | |
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) | |
{ | |
var property = base.CreateProperty(member, memberSerialization); | |
if (IsIgnored(property.PropertyType.Name, property.PropertyName)) | |
{ | |
property.ShouldSerialize = i => false; | |
property.Ignored = true; | |
} | |
return property; | |
} | |
bool IsIgnored(string typeName, string propertyName) | |
{ | |
return ignores.Any(r => r.IsMatch(typeName)) || ignores.Any(r=>r.IsMatch(propertyName)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment