Json.NET: Deserilization with Double Quotes
Asked Answered
E

6

12

I am trying to deserialize a json string received as a response from the service. The client is Windows Phone 7, in C#. I am using Json .NET - James Newton-King deserializor to directly convert the Json string to objects. But sometimes the Json string contains some comments information with double quotes (") in them and the deserializer fails and throws an error. Looks like this is an invalid Json string according to Jsonlint.

{
    "Name": "A1",
    "Description": "description of the "object" A1"
}

How to handle such Json String. If it is (\"), then it works. But I cannot replace all (") with (\") as there might be double quotes in other part of the json string. Is there any decode function of Json .Net?

Epigraphy answered 13/11, 2011 at 3:50 Comment(1)
try to use custom deserialization this post in SO may help you[How to convert json object to custom type before deserializing?][1] [1]: #6976289Libratory
H
14

It looks like HttpUtility.JavaScriptStringEncode might solve your issue.

HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(yourObject))
Herring answered 8/2, 2013 at 12:16 Comment(0)
U
3

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);
Unsnap answered 22/3, 2019 at 14:59 Comment(1)
Very nice solution. It should be considered as correct answer.Xanthene
H
2

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

Hanafee answered 22/1, 2014 at 20:35 Comment(0)
L
1

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.

Lakendra answered 25/10, 2018 at 18:9 Comment(1)
Throwing exceptions to handle the problem; is performance not a serious issue here?Chromite
C
0

you can use newtonsoft library to convert it to object( to replace \" with "):

dynamic o = JObject.Parse(jsondata);
return Json(o);
Coalfish answered 21/7, 2019 at 6:34 Comment(0)
S
0

It has another solution. I try to replace \" after JsonConvert.SerializeObject(yourObject), and it successfully parses from the SerializeObject.

The following code

JsonConvert.SerializeObject(yourObject).Replace("\\\"", "\\\\\"")

Example:

The original text "description of the \"object\" A1" transfer to "description of the \\"object\\" A1".

Soluk answered 6/5 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.