我想对继承 System.Exception 的自定义异常对象进行 JSON 序列化。 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 属性。他们没有帮助。我如何让它发挥作用?
最佳答案
因为 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));
关于c# - JSON.NET 忽略从 System.Exception 派生的类型中的属性。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27197317/