我想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();
}
}
我尝试在正确的位置添加DataContract和DataMember属性。他们没有帮助。我如何让它工作?
答案 0 :(得分:15)
因为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));
答案 1 :(得分:8)
您还可以通过覆盖System.Runtime.Serialization.SerializationInfo
方法和GetObjectData
ctor(SerializationInfo, StreamingContext)
商店中添加和检索特定对象
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
属性将包含在序列化和反序列化中。