Json.NET: Deserilization with Double Quotes

I had the same problem and i found a possible solution. The idea is to catch the JsonReaderException. This exception bring to you the attribute "LinePosition". You can replace this position to an empty character (' '). And then, you use this method recursively until whole json is fixed. This is my example:

private JToken processJsonString(string data, int failPosition)
        {
            string json = "";
            var doubleQuote = "\"";

            try
            {
                var jsonChars = data.ToCharArray();

                if (jsonChars[failPosition - 1].ToString().Equals(doubleQuote))
                {
                    jsonChars[failPosition - 1] = ' ';
                }

                json = new string(jsonChars);

                return JToken.Parse(json);
            }
            catch(JsonReaderException jsonException)
            {
                return this.processJsonString(json, jsonException.LinePosition);
            }               
        }

I hope you enjoy it.


You can improving this.

    static private T CleanJson<T>(string jsonData)
    {
        var json = jsonData.Replace("\t", "").Replace("\r\n", "");
        var loop = true;
        do
        {
            try
            {
                var m = JsonConvert.DeserializeObject<T>(json);
                loop = false;
            }
            catch (JsonReaderException ex)
            {
                var position = ex.LinePosition;
                var invalidChar = json.Substring(position - 2, 2);
                invalidChar = invalidChar.Replace("\"", "'");
                json = $"{json.Substring(0, position -1)}{invalidChar}{json.Substring(position)}";
            }
        } while (loop);
        return JsonConvert.DeserializeObject<T>(json);
    }

Example;

var item = CleanJson<ModelItem>(jsonString);

Just do:

yourJsonString = yourJsonString.Replace("\"", "\\u022");
object o = JSonConvert.Deserialize(yourJsonString);

\u022 is the ascii code for double quotes. So replacing quotes for \u022 will be recognized by your browser.

And use \ in "\u022" to make c# recognize backslash character.

Cheers


It looks like HttpUtility.JavaScriptStringEncode might solve your issue.

HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(yourObject))