1

I'm using the WebApi httpclient to build up a .net api library for use against a REST webservice.

The rest service returns JSON.

Problem i am having is that for one request, it is possible that i get diffrent JSON formats back.

If the query was successful, I get back a JSON array which I have made a strong c# type to hold it.

Using the ReadAsAsync< T > method to get it out of the content.

If the request had a bad api key in or another error happens, the rest service returns a JSON object with some properties like status=error and an explanation message etc.

I cant then just use the ReadAsAsync< T > method as I dont know what format is comming back. I don't know much about the JSON linq library but is there a way I can put the JSON response into some JSON holder object and then check if there is a status=error in it and then use the correct deserialization to my strong type.

I seem to be able to store it in a JRaw object but don't know where to go from here.

Many thanks.

2 Answers 2

1

If the request had a bad api key in or another error happens, the rest service returns a JSON object with some properties like status=error and an explanation message etc.

In this case, the status code returned will not be successful. You can do a check on the status code and then deserialize your response content appropriately:

        if (httpResponseMessage.IsSuccessStatusCode)
        {
           // Deserialize your JSON array
        }
        else
        {
           // Deserialize the error
        }
Sign up to request clarification or add additional context in comments.

Comments

0

You can use error handling in this case

try
{
      //Deserialize your JSON Array..this will throw an exception in case of type mismatch
}
catch(Exception e)
{
     //Deserialize your JSON object which will give you Error code or message
}

Comments

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.