Json.NET: Deserilization with Double Quotes

爱⌒轻易说出口 提交于 2020-01-11 05:57:09

问题


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?


回答1:


It looks like HttpUtility.JavaScriptStringEncode might solve your issue.

HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(yourObject))



回答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




回答3:


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.




回答4:


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);



回答5:


I would recommend to write email to server admin/webmaster and to ask them fix this issue with json.

But if this is impossible, you can write simple parse that finds nonescaped doublequotes inside doublequotes and escapes them. It will hardly be >20lines of code.




回答6:


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

dynamic o = JObject.Parse(jsondata);
return Json(o);


来源:https://stackoverflow.com/questions/8109464/json-net-deserilization-with-double-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!