Can JSON.NET serialize/deserialize System.Exception?

Nov 23, 2010 at 9:41 PM
I logged this as a bug just in case, but does anyone know if this is supposed to work?
I'm not sure if JSON.Net supports serializing/deserializing exceptions. If so, it looks like there is a problem if the Exception.Data member has been accessed.

This succeeds on deserailization: "{\"Exceptions\":[{\"ClassName\":\"System.Exception\",\"Message\":\"Test Exception\",\"Data\":null,
This Fails on deserailization:        "{\"Exceptions\":[{\"ClassName\":\"System.Exception\",\"Message\":\"Test Exception\",\"Data\":{},

Test case below:

[Test]
public void SerializeException1()
{
ClassWithException classWithException = new ClassWithException();
try
{
throw new Exception("Test Exception");
} catch(Exception ex)
{
classWithException.Exceptions.Add(ex);
}
string sex = JsonConvert.SerializeObject(classWithException);
ClassWithException dex = JsonConvert.DeserializeObject<ClassWithException>(sex);
Assert.AreEqual(dex.Exceptions[0].ToString(),dex.Exceptions[0].ToString());

var data = classWithException.Exceptions[0].Data;

sex = JsonConvert.SerializeObject(classWithException);
//sex =
// "{\"Exceptions\":[{\"ClassName\":\"System.Exception\",\"Message\":\"Test Exception\",\"Data\":{},\"InnerException\":null,\"HelpURL\":null,\"StackTraceString\":\" at Newtonsoft.Json.Tests.JsonConvertTest.SerializeException() in C:\\\\Svn\\\\JSON.Net\\\\trunk\\\\Src\\\\Newtonsoft.Json.Tests\\\\JsonConvertTest.cs:line 332\",\"RemoteStackTraceString\":null,\"RemoteStackIndex\":0,\"ExceptionMethod\":\"8\\nSerializeException\\nNewtonsoft.Json.Tests, Version=3.5.0.0, Culture=neutral, PublicKeyToken=null\\nNewtonsoft.Json.Tests.JsonConvertTest\\nVoid SerializeException()\",\"HResult\":-2146233088,\"Source\":\"Newtonsoft.Json.Tests\",\"WatsonBuckets\":null}]}";

dex = JsonConvert.DeserializeObject<ClassWithException>(sex); // this fails!
Assert.AreEqual(dex.Exceptions[0].ToString(), dex.Exceptions[0].ToString());
}