目标
基于分别代表父类和属性的Type
和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);