通过反射进行动态json序列化过滤



我想为json.net创建一个动态契约解析器,它将在运行时排除字段。这个想法是将一些传递到构造函数中,它将排除CreateProperties覆盖中的某些字段。

到目前为止,我提出了传递PropertyInfo[],它依赖于Json/Class属性名称相等,这在长期来看是不好的(即,我想将Json属性名称重写为更短的名称)。解决方案的另一个问题是,我需要通过PropertyInfo[],这在我看来并不直观。

也许有一种方法可以使用LINQ表达式以更好的方式重写这个类。例如,传递List<Func<T,TOut>>,然后通过反射编译和提取参数。它将更加动态,但不会解决Json/Class属性名称相等的问题。

有什么建议吗,我被卡住了。。。。

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;
    }
}

这里有一个实现,它接受任意数量的Expression<Func<T, object>>,并排除它们引用的属性。从表达式中提取属性名称的代码取自此答案。

public class DynamicContractResolver<T> : DefaultContractResolver
{
    private readonly HashSet<string> propertiesToExclude;
    public DynamicContractResolver(
        params Expression<Func<T, object>>[] propertyExpressions)
    {
        this.propertiesToExclude = new HashSet<string>();
        foreach (Expression<Func<T, object>> expression in propertyExpressions)
        {
            string propertyName = GetPropertyNameFromExpression(expression);
            this.propertiesToExclude.Add(propertyName);
        }
    }
    protected override IList<JsonProperty> CreateProperties(
        Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> jsonProperties =
            base.CreateProperties(type, memberSerialization);
        if (typeof(T).IsAssignableFrom(type))
        {
            jsonProperties = jsonProperties
                .Where(pr => !this.propertiesToExclude.Contains(pr.PropertyName))
                .ToList();
        }
        return jsonProperties;
    }
    // https://stackoverflow.com/a/2916344/497356
    private string GetPropertyNameFromExpression(
        Expression<Func<T, object>> expression)
    {
        MemberExpression body = expression.Body as MemberExpression;
        if (body == null)
        {
            UnaryExpression ubody = (UnaryExpression)expression.Body;
            body = ubody.Operand as MemberExpression;
        }
        return body.Member.Name;
    }
}

这里有一个使用它的例子:

var resolver = new DynamicContractResolver<MyClass>(
    mc => mc.MyIntegerProperty,
    mc => mc.MyBoolProperty);
var myClass = new MyClass
{
    MyIntegerProperty = 4,
    MyStringProperty = "HELLO",
    MyBoolProperty = true
};
var settings = new JsonSerializerSettings
{
    ContractResolver = resolver,
    Formatting = Newtonsoft.Json.Formatting.Indented
};
string serialized = JsonConvert.SerializeObject(
    myClass, settings);
Console.WriteLine(serialized);

相关内容

  • 没有找到相关文章