Difficulty with parsing error JSON from ServiceNow REST API
Given that the web service isn't properly returning an error status, you could parse to an intermediate JToken
then check to see if the response looks like an error or not:
var token = JToken.Parse(response.Content);
if (token.Type == JTokenType.Object && ((JToken)"failure").Equals(token["status"]))
{
// Handle error explicitly
return null;
}
var dataset = token.ToObject<DataSet>();
var results = dataset.Tables["result"];
return results;
Alternatively you could catch the JsonException
and check for an explicit error. I don't really recommend this approach since it depends on the fact that the JSON for an error cannot be coincidentally deserialized as the JSON for a DataSet
:
try
{
try
{
var dataset = JsonConvert.DeserializeObject<DataSet>(response.Content);
var results = dataset.Tables["result"];
return results;
}
catch (JsonException)
{
var token = JToken.Parse(response.Content);
if (token.Type == JTokenType.Object && ((JToken)"failure").Equals(token["status"]))
{
// Handle error explicitly
return null;
}
// OK, it's not an explicit error. rethrow
throw;
}
}
catch (Exception ex)
{
// Generic error in the code somewhere.
Debug.WriteLine(ex);
// ... Other error handling as required
}