Parsing of invalid strings

Sep 3, 2008 at 10:47 AM

This is a minor issue, but the when parsing an invalid string like the following:

@"this is a string ""that has quotes"" ";

JSON.NET will deserialize this string as:

this is a string

The expected behavior here should probably be an exception that the string is invalid.

As I mentioned this is a fairly minor issue, since hopefully there should never be invalid JSON coming in, but I actually have had several customers who are generating their own JSON with XSL and occasionally the generated JSON is invalid. Invalid strings like this end up failing silently with incorrect data.

Here's a test for this:

        [TestMethod]
        public void TestInvalidStrings()
        {
            string orig = @"this is a string ""that has quotes"" ";
            string serialized = ser.Serialize(orig);

            // *** Make string invalid by stripping \" \"
            serialized = serialized.Replace(@"\""", "\"");

            TestContext.WriteLine("Invalid JSON string to deserialize: {0}", serialized);

            string result = null;
             result = ser.Deserialize(serialized, typeof(string)) as string;

            Assert.IsNull(result, "Should be null. Orig json: [" + serialized + "]  Result: [" + result + "]");
        }

Thanks,

+++ Rick ---
Coordinator
Sep 4, 2008 at 8:16 AM
Nice find. I have updated JavaScriptConvert.DeserializeObject so that it errors if there is addition content in the string after the object has been deserialized.