首页 > 解决方案 > 如何使用 Utf8Json 实现基于属性类型的属性黑名单?

问题描述

目标

基于 aTypestring分别表示父类和属性,我想在序列化时过滤属性。

我知道 Utf8Json(和 Newtonsoft 就此事而言)支持现场属性,但由于代码库的原因,我想根据存储在字典中的已定义黑名单来执行此操作。

已经使用 Newtonsoft 的示例

目前,Newtonsoft.Json我有类似于以下代码的包(为简洁起见)。

public class ShouldSerializeContractResolver : DefaultContractResolver
{
    public Dictionary<Type, string> SerializeBlackList { get; set; }

    public ShouldSerializeContractResolver()
    {
        SerializeBlackList = new Dictionary<Type, string> {
            { typeof(Shape), "ShapePropertyFoo" },
            { typeof(Shape), "ShapePropertyBar" },
        };
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        if (SerializeBlackList == null || SerializeBlackList?.ContainsKey(type) == false)
        {
            return base.CreateProperties(type, memberSerialization);
        }

        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        return properties.Where(p => SerializeBlackList[type] != p.PropertyName).ToList();
    }
}

稍后实例化,存储在变量中并调用序列化。

var fooSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new ShouldSerializeContractResolver()
                    });
var resultString = JsonConvert.SerializeObject(results, Formatting.None, fooSettings);

标签: c#jsonsystem.text.json

解决方案


推荐阅读