I want to create a dynamic contract resolver for json.net which will exclude fields in runtime. The idea is to pass into constructor something which will exclude certain fields inside CreateProperties override.
So far i came up with passing PropertyInfo[]
which relies on Json / Class properties name equality which is not good in long run ( ie. i want to override json property name to something shorter ). Another issue with solution is that i need to pass PropertyInfo[]
which is not intuitive in my opinion.
Maybe there is a way to use LINQ expressions to rewrite this class in better way. For example like passing List<Func<T,TOut>>
then compiling and extracting parameters via reflection. It will be more dynamic but would not solve the issue with Json / Class property name equality.
Any suggestions, i'm stuck....
public class DynamicContractResolver : DefaultContractResolver
{
private readonly PropertyInfo[] m_propertiesExclusion;
public DynamicContractResolver(PropertyInfo[] propertiesExclusion)
{
m_propertiesExclusion = propertiesExclusion;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> jsonProperties = base.CreateProperties(type, memberSerialization);
IEnumerable<string> filteredOutProperties = m_propertiesExclusion.Select(i => i.Name);
jsonProperties = jsonProperties
.Where(i => !filteredOutProperties.Contains(i.PropertyName))
.ToList();
return jsonProperties;
}
}