gpt4 book ai didi

c# - 尝试序列化异常时忽略自定义解析器

转载 作者:太空宇宙 更新时间:2023-11-03 12:02:06 25 4
gpt4 key购买 nike

我想使用自定义解析器序列化一个Exception

这是一个示例自定义解析器 - 它应该只序列化指定的属性:

public class IncludeSpecifiedPropsResolver : DefaultContractResolver
{
string[] propsToSerialize = null;
public IncludeSpecifiedPropsResolver(params string[] propsToSerialize)
{
this.propsToSerialize = propsToSerialize;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var allProps = base.CreateProperties(type, memberSerialization);
if (propsToSerialize == null || propsToSerialize.Length == 0)
{
return allProps;
}
return allProps.Where(p => propsToSerialize.Contains(p.PropertyName)).ToList();
}
}

示例用法:

string test = JsonConvert.SerializeObject(new Exception("Something went wrong"), new JsonSerializerSettings()
{
ContractResolver = new IncludeSpecifiedPropsResolver("Message")
});

但是,CreateProperties 会被忽略。

为了使自定义解析器能够按预期工作,还缺少什么?

最佳答案

这里的问题是 Exception 实现了 ISerializable接口(interface),它在 DefaultContractResolver 中有特殊处理:代码路径不经过 CreateProperties()。您可以通过设置 IgnoreSerializableInterface 来覆盖此行为在解析器的构造函数中将属性设置为 true。如果这样做,您的代码将按预期工作。

public IncludeSpecifiedPropsResolver(params string[] propsToSerialize)
{
this.propsToSerialize = propsToSerialize;
IgnoreSerializableInterface = true;
}

工作演示:https://dotnetfiddle.net/DNhwaH

关于c# - 尝试序列化异常时忽略自定义解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56651414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com