尝试反序列化从Exception继承的类时,Json.net失败

时间:2013-01-06 19:44:32

标签: c# json json.net

我有一个继承自SearchError的类Exception,当我尝试从有效的json反序列化时,我得到以下异常:

ISerializable type 'SearchError' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present. Path '', line 1, position 81.

我尝试实现建议的缺失构造函数,但没有帮助。

这是实现建议的构造函数后的类:

public class APIError : Exception
{
    [JsonProperty("error")]
    public string Error { get; set; }

    [JsonProperty("@http_status_code")]
    public int HttpStatusCode { get; set; }

    [JsonProperty("warnings")]
    public List<string> Warnings { get; set; }

    public APIError(string error, int httpStatusCode, List<string> warnings) : base(error)
    {
        this.Error = error;
        this.HttpStatusCode = httpStatusCode;
        this.Warnings = warnings;
    }

    public APIError(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
        : base(info, context)
    {
        Error = (string)info.GetValue("error", typeof(string));
        HttpStatusCode = (int)info.GetValue("@http_status_code", typeof(int));
        Warnings = (List<string>)info.GetValue("warnings", typeof(List<string>));
    }
}

现在我收到以下异常(也在json.net代码中):

Member 'ClassName' was not found.

我也尝试实现与this related question中相同的解决方案,也遇到了同样的错误。

2 个答案:

答案 0 :(得分:10)

此问题已在此处得到解答:https://stackoverflow.com/a/3423037/504836

添加新构造函数

public Error(SerializationInfo info, StreamingContext context){}

解决了我的问题。

这里有完整的代码:

[Serializable]
public class Error : Exception
{

    public string ErrorMessage { get; set; }

    public Error(SerializationInfo info, StreamingContext context) {
        if (info != null)
            this.ErrorMessage = info.GetString("ErrorMessage");
    }
    public override void GetObjectData(SerializationInfo info,StreamingContext context)
    {
        base.GetObjectData(info, context);

        if (info != null)
            info.AddValue("ErrorMessage", this.ErrorMessage);
    }
}

答案 1 :(得分:3)

如错误所示,您缺少序列化构造函数:

public class SearchError : Exception
{
    public SearchError(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
    {

    }
}