问题
I have a class SearchError
that inherits from Exception
, and when ever I try to deserialize it from a valid json I get the following 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.
I tried implementing the suggested missing constructor, and it didn't help.
This is the class after implementing the suggested constructor:
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>));
}
}
Now I'm getting the following exception (also in json.net code):
Member 'ClassName' was not found.
I also tried implementing the same solution as in this related question, also got the same error above.
回答1:
This question has been answered here: https://stackoverflow.com/a/3423037/504836
Adding a new constructor
public Error(SerializationInfo info, StreamingContext context){}
solved my problem.
Here complete code:
[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);
}
}
回答2:
As the error says, you are missing the serialization constructor:
public class SearchError : Exception
{
public SearchError(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
}
来源:https://stackoverflow.com/questions/14186000/json-net-fails-when-trying-to-deserialize-a-class-that-inherits-from-exception