Incorrect deserialization when string contains double qoutes

Hello,

I am trying to validate a json string that is passed to my application. Whenever my string contains double quotes things get a little murky. I’m a trying to deserialize an invalid json string, something like “A"B”.

I’ve tried to following:

JsonSerializer.DeserializeFromString<String>("\"A\"B\"")

This will return: “A”, I expected an error

When I try to use the JsonObject.Parse method with the same string

JsonObject.Parse("\"A\"B\"")

It will return an object with the following value: {[A"B", ]}, the final double quote does not make sense to me, and I would also expect an error.

If I try to do the same with the following string:

JsonSerializer.DeserializeFromString<String>(@"""A""B""")

The return value will be “A”, which makes no sense as this is not a valid json string.
If I try to do the same with the JavascriptSerializer

var a = new JavaScriptSerializer();
var res = a.Deserialize<string>("\"A\"B\"");

it will throw an error because it’s not valid JSON. Which is what I expect.

For now I deserialize the string and serialize it again and see if it matches the original string, if not I consider the parsing failed and throw my own error, but something seems off here. Maybe somebody can explain whether I am doing something wrong or if this is a bug.

Kind regards,
Guido

The ServiceStack.Text JSON Serializers typically try to deserialize as much as possible without error so they’re not useful for detecting invalid JSON.

You could try using the JavaScript utils in ServiceStack Templates which is an alternative implementation for parsing JS/JSON literals, e.g:

JSON.parse("\"A\"B\"");

Thanks for your quick reply, I will try it out and see if I can detect incorrect JSON!