Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisfcarroll/50fe9a235f388e285a05af8c31852b08 to your computer and use it in GitHub Desktop.
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
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;
}
}
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