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

前端 未结 3 1786
时光取名叫无心
时光取名叫无心 2020-12-03 21:10

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

[Serializable]
public class Error : Exception, ISerializable
{
    public string ErrorMessage         


        
相关标签:
3条回答
  • 2020-12-03 21:48

    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)

    0 讨论(0)
  • 2020-12-03 21:50

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-03 22:04

    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");**
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题