c# - 如何使用 Utf8Json 实现基于属性类型的属性黑名单?
问题描述
目标
基于 aType
和string
分别表示父类和属性,我想在序列化时过滤属性。
我知道 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);
解决方案
推荐阅读
- sql - 加入四张表结果正确加入第五张表后出现重复和错误结果
- python - 使用 pip3 在 Windows 10 设备上安装 Jupyter 时出错 - 正在安装 Jupyter 1.0.0,但未运行
- python - 将html字符串拆分为列表
- javascript - 在 reactjs 中更新嵌套状态
- css - 需要消除我网站上的“添加菜单”文本
- email - Mailchimp DATE Merge Tag in URL updating after email sent
- python-3.x - 如何获得刻度标签、xlabel 或 ylabel 的扩展?
- c# - 如果我使用长时间运行的子窗口,如何停止 wpf 中的自动锁定功能?
- php - 使用ajax读取加密的php文件
- javascript - vuex : $store.commit vs 直接调用函数