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.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
Serialization or deserialization errors will typically result in a JsonSerializationException .
The exception thrown when an error occurs during JSON serialization or deserialization.
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With