Tag Archives: JSON

JSON or not JSON: that is the question

When you write unit tests for a REST API, you probably want to test whether the given response is in the expected format. For example you want to ensure, that the response string is a valid JSON or not.

You can find a very simple tip on StackOverflow and in other blogs as well: just check whether the first character of the response is a < or { character, because JSON is about Object Notation, right? The problem with this approach is not only that it does not perform a thorough analysis, but also that its basic statement is simply not true. According to json.org, a JSON can also contain only a single value, the specification does not require it to be an object or an array at all:

json-value

So I love JSON, 123, true and false are all valid JSON strings.

Unfortunately I could not find a simple IsValidJson method, but I could come up with this solution using Newtonsoft JSON.NET library:

try
{
    JToken.Parse(input);
    return true;
}
catch (JsonReaderException)
{
    return false;
}

Is there a better solution?

 

Technorati-címkék: ,,