Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize object derived from Exception class using Json.net?

I'm trying to deserialize object derived from Exception class:

[Serializable]
public class Error : Exception, ISerializable
{
    public string ErrorMessage { get; set; }
    public Error() { }
}
Error error = JsonConvert.DeserializeObject< Error >("json error obj string"); 

It gives me error:

ISerializable type 'type' does not have a valid constructor.

like image 752
Piotr Avatar asked Aug 06 '10 09:08

Piotr


3 Answers

Alternatively, you can choose the OptIn strategy and define the properties that should be processed. In case of your example:

[JsonObject(MemberSerialization.OptIn)]
public class Error : Exception, ISerializable
{
    [JsonProperty(PropertyName = "error")]
    public string ErrorMessage { get; set; }

    [JsonConstructor]
    public Error() { }
}

(Credits go to this library)

like image 34
Martijn Avatar answered Nov 15 '22 11:11

Martijn


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);
    }
}
like image 89
Piotr Avatar answered Nov 15 '22 13:11

Piotr


Adding upon already provided nice answers;

If the exception is coming from a java based application, then above codes will fail.

For this, sth. like below may be done in the constructor;

public Error(SerializationInfo info, StreamingContext context)
{
    if (info != null)
    {
        try
        {
            this.ErrorMessage = info.GetString("ErrorMessage");
        }
        catch (Exception e) 
        {
            **this.ErrorMessage = info.GetString("message");**
        }
    }
}
like image 2
myuce Avatar answered Nov 15 '22 11:11

myuce