I'm using Json.net in a 3.5 CF setting and have a problem verifying that a string is indeed complete JSON.
I am using:
var o = JObject.Parse(incomingString);
which will return null if the JSON is incomplete - but not always. If the JSON is something "mostly formed", it will parse correctly. This simple example returns an object:
{ "Name":"Bob", "Pets":[ {"Type":"Cat", "Name":"Pudge"
but if I break the JSON elsewhere, it returns null as expected.
{ "Name":"Bob", "Pets":[ {"Type":"Cat", "Nam
With no closing brackets it seems to "assume" those brackets and returns a proper JObject, but since this JSON data is streaming in I need to verify that all brackets are matched before I process it.
In our limited sandbox, I don't seem to have any of the validation methods available on the newer APIs. Any suggestions for verifying that I have the entire JSON before I process it? Thanks.
OK, it was fixed in Json.NET 4.0.1: Fixed JToken Load and Parse methods not checking for incomplete content, but your're stuck on 35r8 because that's the last version that supports the compact framework. In that case, the following static helper methods will check that the start and end depths match:
public static class Json35Extensions
{
public static JObject ParseObject(string json)
{
using (var reader = new JsonTextReader(new StringReader(json)))
{
var startDepth = reader.Depth;
var obj = JObject.Load(reader);
if (startDepth != reader.Depth)
throw new JsonSerializationException("unclosed json found");
return obj;
}
}
public static JArray ParseArray(string json)
{
using (var reader = new JsonTextReader(new StringReader(json)))
{
var startDepth = reader.Depth;
var obj = JArray.Load(reader);
if (startDepth != reader.Depth)
throw new JsonSerializationException("unclosed json found");
return obj;
}
}
}
Using Json.NET 3.5.8, for both your test JSON strings, the exception gets thrown, but if I fix your JSON manually there is no exception. (Note - I tested the ParseObject
version but I haven't tested the ParseArray
version.)