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();
}
}
I've tried adding the DataContract and DataMember attributes in the correct places. They don't help. How do I get this to work?
Best Answer
Because Exception implements
ISerializable
, Json.Net uses that to serialize the object by default. You can tell it to ignoreISerializable
like so: