I have a custom Exception :
[Serializable]
public class MyCustomException : Exception
{
public List<ErrorInfo> ErrorInfoList { get; set; }
protected MyCustomException (SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.ErrorInfoList = (List<ErrorInfo>)info.GetValue("ErrorInfoList", typeof(List<ErrorInfo>));
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("ErrorInfoList ", this.ErrorInfoList, typeof(List<ErrorInfo>));
base.GetObjectData(info, context);
}
}
Whenever it tries to deserialize, this line throws an "Object must implement IConvertible" exception: (List<ErrorInfo>)info.GetValue("ErrorInfoList", typeof(List<ErrorInfo>))
Here's the bit of code that does the serialization:
using(MemoryStream memStm = new MemoryStream())
{
XmlObjectSerializer ser = new DataContractJsonSerializer(
typeof(MyCustomException),
new Type[] {
typeof(List<ErrorInfo>),
typeof(ErrorInfo)
}
);
ser.WriteObject(memStm, (MyCustomException)context.Exception);
memStm.Seek(0, SeekOrigin.Begin);
using (StreamReader streamReader = new StreamReader(memStm))
{
response.Content = new StringContent(streamReader.ReadToEnd());
}
}
Here's the bit of code that does the deserialization:
using(MemoryStream memStm = new MemoryStream(response.Content.ReadAsByteArrayAsync().Result))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(
typeof(MyCustomException),
new Type[] {
typeof(List<ErrorInfo>),
typeof(ErrorInfo)
}
);
UserPortalException upEx = (UserPortalException)deserializer.ReadObject(memStm);
throw upEx;
}
Here's the code for the ErrorInfo class:
[Serializable]
public class ErrorInfo : ISerializable
{
public enum ErrorCode {
[.....]
}
public ErrorCode Code { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Code", this.Code , typeof(ErrorCode ));
}
public Error(SerializationInfo info, StreamingContext context)
{
this.Code = (ErrorCode)Enum.Parse(typeof(ErrorCode), info.GetInt32("Code").ToString());
}
}