尝试反序列化从Exceptioninheritance的类时,Json.net失败
我有一个inheritance自Exception
的类SearchError
,当我尝试从有效的json反序列化时,我得到以下exception:
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 Warnings { get; set; } public APIError(string error, int httpStatusCode, List 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)info.GetValue("warnings", typeof(List)); } }
现在我得到以下exception(也在json.net代码中):
Member 'ClassName' was not found.
我也尝试实现与此相关问题相同的解决方案,也得到了相同的错误。
这个问题已在这里得到解答: 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); } }
正如错误所说,您缺少序列化构造函数:
public class SearchError : Exception { public SearchError(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } }