Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.