2

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.

1 Answer 1

2

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>();
Sign up to request clarification or add additional context in comments.

3 Comments

This does not work unfortunately. I am getting a "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."
Added json examples to the original post
I corrected the solution to take into account that your object is an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.