wingyip wingyip - 1 year ago 104
C# Question

Get JSON.Net to throw Exception if object not of expected type in Generic method

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


Which successfully returns an object of Type

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


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.

Answer Source

There no JsonSerializationException because the Json is well formated but no property match with the properties of the type T. So the result is a new T object.

I would say that the following code should work :

//First, convert to JToken 
var o = JsonConvert.DeserializeObject<JToken>(input);
//Then check if the property error exists
if(!(o is JArray) && o["error"] != null);
     throw new Exception(...)      
//Finally convert the object
return o.ToObject<T>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download