Reputation: 1809
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
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