JSON.NET忽略从System.Exception派生的类型的属性.为什么? [英] JSON.NET is ignoring properties in types derived from System.Exception. Why?
问题描述
我想对继承自System.Exception的自定义异常对象进行JSON序列化.JsonConvert.SerializeObject似乎忽略了派生类型的属性.这个问题可以很简单地说明:
I want to JSON serialize a custom exception object which inherits System.Exception. JsonConvert.SerializeObject seems to ignore properties from the derived type. The problem can be illustrated very simply:
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属性.他们没有帮助.我如何使它工作?
I've tried adding the DataContract and DataMember attributes in the correct places. They don't help. How do I get this to work?
推荐答案
由于Exception实现了 ISerializable
,因此Json.Net会默认使用它来序列化对象.您可以像这样告诉它忽略 ISerializable
:
Because Exception implements ISerializable
, Json.Net uses that to serialize the object by default. You can tell it to ignore ISerializable
like so:
var settings = new JsonSerializerSettings() {
Formatting = Formatting.Indented,
ContractResolver = new DefaultContractResolver() {
IgnoreSerializableInterface = true
}
};
Console.WriteLine(JsonConvert.SerializeObject(new MyException {MyProperty = "foobar"}, settings));
这篇关于JSON.NET忽略从System.Exception派生的类型的属性.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!