Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET: Deserilization with Double Quotes

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?

like image 825
franklins Avatar asked Nov 13 '11 03:11

franklins


People also ask

Does JSON support double quotes?

JSON names require double quotes.

How do I allow double quotes in JSON?

If you're making a . json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes: \" is the one you're looking for.

Does JSON care about single or double quotes?

Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .

Why does JSON require double quotes?

Yes. Properties in JSON have to be strings, and in JSON as string is defined as "a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes". In other words using single quotes, or no quotes at all is not allowed.


2 Answers

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);
like image 100
dcansyn Avatar answered Oct 11 '22 20:10

dcansyn


It looks like HttpUtility.JavaScriptStringEncode might solve your issue.

HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(yourObject))
like image 44
ITmeze Avatar answered Oct 11 '22 20:10

ITmeze