【发布时间】:2016-10-14 16:40:23
【问题描述】:
我有一个自定义异常:
[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);
}
}
每当它尝试反序列化时,此行都会引发“对象必须实现 IConvertible”异常:(List<ErrorInfo>)info.GetValue("ErrorInfoList", typeof(List<ErrorInfo>))
这是执行序列化的代码:
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());
}
}
下面是反序列化的代码:
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;
}
这是 ErrorInfo 类的代码:
[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());
}
}
【问题讨论】:
-
抛出的错误是不言自明的还是这里还有其他问题?
-
我不明白如何修复异常...哪个类需要实现IConvertible?
-
ErrorInfo 类的代码在哪里?
-
我刚刚将它添加到问题中。
标签: c# serialization deserialization datacontractserializer datacontractjsonserializer