I created a generic deserialization method that I pass a json string into. T is the type that I want returned.
private static T Deserialize<T>(string input)
{
try
{
var result = JsonConvert.DeserializeObject<T>(input);
return result;
}
catch (JsonSerializationException ex)
{
var errorResult = JsonConvert.DeserializeObject<Dictionary<string, string>>(input);
var errorMessage = errorResult["error"];
throw new ApplicationException(errorMessage, ex);
}
}
So to call the method we choose
Deserialize<MyObject>(jsonString)
Which successfully returns an object of Type MyObject.
However, the json passed in can sometimes contain an error message (error : message) if things have gone wrong.
What I wanted to do in this case is cause a JsonSerializationException and read the error message.
However, no such error is thrown and the MyObject is retured but with all null and zero values.
Error json
"{\"error\":\"Error message"}"
Other json
"[{\"path\":\"\",\"id\":2000,\"name\":\"Name1\"},{\"path\":\"\",\"id\":2001,\"name\":\"Name2\"},{\"path\":\"\",\"id\":2002,\"name\":\"Name3\"}]"
The other json could be in pretty much any format - but the point is that the required Type is passed into the method and that is what should get returned or an exception should be thrown.