I have the following setup for deserializing some json:
parsedResponse = JsonConvert.DeserializeObject<T>(
json,
new JsonSerializerSettings
{
Error = (object sender, ErrorEventArgs args) =>
{
throw new MyParseException($"Parse error: {args.ErrorContext.Error.Message}");
},
Converters =
{
new MyItemConverter(),
new BoolConverter(),
new UnixDateTimeConverter(),
new NullableIntConverter(),
new UriConverter()
}
}
);
In one case, json
has a bunch of null values (like "title" : null,
etc) which causes a NullReferenceException in one of my converters. But throwing MyParseException
in the error handler causes
System.InvalidOperationException: Current error context error is different to requested error.
I think I could do this instead:
try
{
parsedResponse = JsonConvert.DeserializeObject<T>(
json,
new JsonSerializerSettings
{
Converters =
{
new MyItemConverter(),
new BoolConverter(),
new UnixDateTimeConverter(),
new NullableIntConverter(),
new UriConverter()
}
}
);
}
catch (Exception ex)
{
throw new MyParseException($"Parse error: {ex.Message}");
}
But is there a better way? (Maybe something more similar to my original solution that doesn't cause the error context issue?)