Christoph Herold
Christoph Herold

Reputation: 1809

How can I validate JSON using .NET libraries that do NOT accept single quoted string tokens?

I would like to validate JSON coming from an external source. The JSON RFC specifically states, that all strings should be wrapped in double quotes and single quotes are not valid. However, both the built-in JavaScriptSerializer and Json.NET's JsonConvert.DeserializeObject accept single quoted strings as valid. Is there a way to tell them not to accept single quoted strings, or is there another library available that validates according to the RFC standard?

Example:

{
    "this": "is",
    "valid": "json"
}

{
    'this': 'is',
    'invalid': 'json',
    'but': 'parsed',
    'correctly': 'by',
    'both': 'parsers',
    'I': 'mentioned'
}

Upvotes: 2

Views: 62

Answers (1)

Johnny Svarog
Johnny Svarog

Reputation: 1146

Please, see this topic, I think, there is something similar to your problem...

Sorry, I was not attentive enough. You might be searching for something like this:

private bool ValidateJson(string json)
        {
            using (var reader = new JsonTextReader(new StringReader(json)))
            {
                while (reader.Read())
                {
                    if (reader.QuoteChar == '\'')
                        return false;
                }
            }

            return true;
        }

Then, let's test this example:

[TestMethod]
    public void SingleQuoteJsonDeserialize()
    {
        var jsonSingle = "{'this': 'is', 'invalid': 'json', 'but': 'parsed', 'correctly': 'by', 'both': 'parsers', 'I': 'mentioned'}";
        var jsonDouble = "{\"this\": \"is\", \"valid\": \"json\"}";

        Assert.AreEqual(false, ValidateJson(jsonSingle));
        Assert.AreEqual(true, ValidateJson(jsonDouble));
    }

Upvotes: 1

Related Questions