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

时间:2014-11-17 21:59:14

标签: json.net

我需要将有关自定义异常类型的信息从WebApi Web服务传递到客户端。为此,我尝试使用Json.Net serializer + 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 =& #34; net45"或包ID =" Newtonsoft.Json" version =" 6.0.6" targetFramework =" net452")

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

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

1 个答案:

答案 0 :(得分:2)

尝试使用它:


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