wingyip wingyip - 1 month ago 14
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)
{
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.

Answer

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>();
Comments