gpt4 book ai didi

Json.net 不会为自定义异常调用自定义 ContractResolver

转载 作者:行者123 更新时间:2023-12-01 03:45:50 28 4
gpt4 key购买 nike

我需要将有关自定义异常类型的信息从 WebApi Web 服务传递到客户端。为此,我尝试使用 Json.Net 序列化程序 + CustomContractResolver 来控制发送给客户端的内容。

public class Data //: Exception
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }

public Data()
{
Prop1 = "Hi";
Prop2 = "Bye";
}
}

public class CustomContractResolver : DefaultContractResolver
{
// !!! Method is not being invoked if Data is inherited from Exception
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = instance => property.PropertyName == "Prop1";
return property;
}
}

class Program
{
static void Main(string[] args)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CustomContractResolver()
};
string json = JsonConvert.SerializeObject(new Data(), settings);

Console.WriteLine(json);
Console.ReadLine();
}
}

我尝试使用 Json.Net 6.0.4 和 6.0.6 运行此代码。正在使用 .Net Framework 4.5.0 和 4.5.2。但问题是一样的 - 当数据从 Exception CustomContractResolver 继承时不起作用(nuget 配置行:package id="Newtonsoft.Json"version="6.0.6"targetFramework="net45"or package id="Newtonsoft.Json "version="6.0.6"targetFramework="net452")

同时,如果代码从 UnitTest 项目 (xUnit.Net) 执行并且代码本身位于具有 .Net 4.5.0 目标平台的 PCL 库中(nuget 配置行:package id="Newtonsoft.Json"),则代码工作正常version="6.0.6"targetFramework="portable-net45+win+wpa81+MonoAndroid10+MonoTouch10")。

有人可以建议如何自定义自定义异常类型的哪些属性将包含在 Json 字符串中吗?

最佳答案

尝试使用这个:


ContractResolver = new CustomContractResolver { IgnoreSerializableInterface = true, IgnoreSerializableAttribute = true };

关于Json.net 不会为自定义异常调用自定义 ContractResolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26982781/

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