When serializing a System.ArgumentNullException
to JSON using JSON.NET, part of the message appears lost:
var json = JsonConvert.SerializeObject(new ArgumentNullException("argument", "Some Message"));
returns:
{
"ClassName":"System.ArgumentNullException",
"Message":"Some Message",
"Data":null,
"InnerException":null,
"HelpURL":null,
"StackTraceString":null,
"RemoteStackTraceString":null,
"RemoteStackIndex":0,
"ExceptionMethod":null,
"HResult":-2147467261,
"Source":null,
"WatsonBuckets":null
}
I expected the Message token to be:
"Some Message\r\nParameter name: argument"
As noted by codefuller, the ArgumentNullException
implements ISerializable
and is the culprit. I can disable this by using custom JsonSerializerSettings
.
However, the application needs to serialize any objects, including objects with an ArgumentNullException
property. I'd prefer to avoid ignoring ISerialiable
unless it presents a problem.
Both of my solutions include a custom JsonConverter
.
Solution 1: Centralized JsonSerializer
- Create a static list of
JsonConverters
to add toJsonSerializer.Converters
- Include an
ExceptionConverter
that handlesArgumentNullException
explicitly - Everywhere I need to serialize, ensure my
JsonSerializer
includes these converters
Cons: other developers must rigorously ensure they are including these converters with any serialization they do.
Solution 2: Override ArgumentNullException
I can create a CustomArgumentNullException
class, and tag it with a JsonConvert
attribute to leverage my custom converter.
Cons: other developers must rigorously ensure they are raising a CustomArgumentNullException
instead of an ArgumentNullExcpetion
.
Wished-for Solution
I'd love to somehow tag the existing ArgumentNullException
with a JsonConverter
attribute pointing to my custom converter. Is there some way to achieve this in the Json.NET code base?