C# – JSON.NET is ignoring properties in types derived from System.Exception. Why

cjsonjson.netserialization

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 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));