How to encode the \'
to \\u0027
with JSON.NET?
So that the json string would look something like this:
{\"Id\":8,\"CompanyName
Json.NET 4.5 Release 11 added an option to control string escaping. One of the options is to escape all HTML characters which includes single quotes.
JsonWriter.StringEscapeHandling
I assumed I had the same requirement, but @nick_w's comment made me realise I didn't need to escape the single quotes at all.
If you are generating json as a string in server side code, then outputting it into the client side javascript, so it can be converted to javascript objects, then escaping is not required.
(Code shown using asp style syntax)
Using extra steps requiring escaping single quotes...
var myData = JSON.parse('<%=myServerGeneratedStringWithSingleQuotesEscaped %>');
Using the JSON as it is...
var myData = <%=myServerGeneratedString %>;
Javascript will interpret an unquoted string such as
[{"name":"Bill"}, {"name":"Ted"}]
as javascript objects.
As it's so easy to get mixed up when dealing with server side and client side strings, this reminder may be useful to someone. It may or may not apply to the OP - I'm sure there are many cases where single quotes genuinely need escaping.
Newtonsoft.Json.JsonConvert.SerializeObject(your_object,
Newtonsoft.Json.Formatting.None,
new Newtonsoft.Json.JsonSerializerSettings
{ StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml })
is what I use when objects may contain an apostrophe, such as user names.
Sample Call
Newtonsoft.Json.JsonConvert.SerializeObject(your_object,
Newtonsoft.Json.Formatting.None,
new Newtonsoft.Json.JsonSerializerSettings
{ StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml })