How to encode the single quote/apostrophe in JSON.NET

亡梦爱人 提交于 2020-01-01 03:11:08

问题


How to encode the ' to \u0027 with JSON.NET?

So that the json string would look something like this:

{"Id":8,"CompanyName":"Jane\u0027s bakery"}

回答1:


Sample Call

 Newtonsoft.Json.JsonConvert.SerializeObject(your_object,
   Newtonsoft.Json.Formatting.None, 
   new Newtonsoft.Json.JsonSerializerSettings 
   { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml })



回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/13541998/how-to-encode-the-single-quote-apostrophe-in-json-net

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