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?
JSON names require double quotes.
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.
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 .
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.
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);
It looks like HttpUtility.JavaScriptStringEncode might solve your issue.
HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(yourObject))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With