我需要将有关自定义异常类型的信息从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 config line:package id =“Newtonsoft.Json”version =“6.0.6”targetFramework =“net45”或package id =“Newtonsoft.Json “version =”6.0.6“targetFramework =”net452“)
同时,如果从UnitTest项目(xUnit.Net)执行代码并且代码本身位于具有.Net 4.5.0目标平台的PCL库中(nuget config line:package id =“Newtonsoft.Json”),则代码工作正常. version =“6.0.6”targetFramework =“portable-net45 win wpa81 MonoAndroid10 MonoTouch10”).
任何人都可以建议如何自定义自定义异常类型的哪些属性将包含在Json字符串中?
最佳答案 试着用这个:
ContractResolver = new CustomContractResolver { IgnoreSerializableInterface = true, IgnoreSerializableAttribute = true };