我想用JSON序列化一个继承System.Exception的自定义异常对象。JsonConvert.SerializeObject 似乎忽略了派生类型的属性。这个问题可以非常简单地说明:
class MyException : Exception {
public string MyProperty { get; set; }
}
class Program {
static void Main(string[] args) {
Console.WriteLine(JsonConvert.SerializeObject(new MyException {MyProperty = "foobar"}, Formatting.Indented));
//MyProperty is absent from the output. Why?
Console.ReadLine();
}
}
我尝试在正确的位置添加数据合同和数据成员属性。他们无济于事。我如何让它工作?
因为 Exception 实现了 ISerializable
,所以默认情况下 Json.Net 使用它来序列化对象。你可以告诉它忽略ISerializable
,如下所示:
var settings = new JsonSerializerSettings() {
Formatting = Formatting.Indented,
ContractResolver = new DefaultContractResolver() {
IgnoreSerializableInterface = true
}
};
Console.WriteLine(JsonConvert.SerializeObject(new MyException {MyProperty = "foobar"}, settings));
通过重写 GetObjectData
方法和ctor(SerializationInfo, StreamingContext)
将特定对象添加和检索到System.Runtime.Serialization.SerializationInfo
存储中:
public class MyCustomException : Exception
{
public string MyCustomData { get; set; }
protected MyCustomException (SerializationInfo info, StreamingContext context) : base(info, context)
{
MyCustomData = info.GetString("MyCustomData");
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("MyCustomData", MyCustomData);
}
}
这样,MyCustomObject
属性将包含在序列化和反序列化中。