1

I have a json string that contains a string literal as value of one of the object - PostData.

string json = "{\"PostData\": '{\"LastName\": \"O Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";

I am trying to deserialize the json using:

var obj = JsonConvert.DeserializeObject<dynamic>(json);

then, I can use my json string value of PostData like:

obj["PostData"].ToString()

But, as soon as I get the data with single quotes in it, like:

string json = "{\"PostData\": '{\"LastName\": \"O' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";

I get exception on deserialization. How can I escape the single quote?

I have checked SO for similar issues but didn't get any thing working. I also tried one of the solution mentioned int his thread:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    StringEscapeHandling =  StringEscapeHandling.EscapeHtml
};

JsonConvert.SerializeObject(obj, settings);

But, I get Newtonsoft doesnot contain defination for StringEscapeHandling.

Also, tried to escape the singlequote with in the string with \: '{\"LastName\": \"O\' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}' which didn't work either.

Community
  • 1
  • 1
Sri Reddy
  • 6,832
  • 20
  • 70
  • 112
  • I assume the best choice is to carefully serialize your object first. Which is Newtonsoft.Json version used? `StringEscapeHandling.EscapeHtml` exists in latest `8.0.3` version and works fine. – Ilya Chumakov Apr 22 '16 at 19:18

1 Answers1

3

For a start, it might be worth noting that the JSON syntax uses single quotes where you have used double quotes. Here is a guide for proper syntax:

JSON Syntax

Now unfortunately JSON does not allow the use of single quotes like that, but we can use the unicode \u0027 for an apostrophe and make use of JSON's serializer settings, as you have already done. So your original string:

string json = "{\"PostData\": '{\"LastName\": \"O' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";

becomes:

string json = "{'PostData': {'LastName': 'O\u0027 Corner','FirstName':'Mark','Address':'123 James St'}}"

This is assuming that you are parsing a string literal, otherwise you would need to escape the unicode to give:

string json = "{'PostData': {'LastName': 'O\\u0027 Corner','FirstName':'Mark','Address':'123 James St'}}"
Jake
  • 915
  • 1
  • 7
  • 22
  • escaping the unicode worked for us i.e. `\u0027` to `\\u0027` – sezmeralda Feb 10 '22 at 01:52
  • How do I replace a single quote to this unicode in the value of a property but not the entire json? because I have dynamic json string in variable. – SPnL Apr 21 '23 at 11:16