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

前端 未结 4 1503
花落未央
花落未央 2021-02-08 18:55

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

So that the json string would look something like this:

{\"Id\":8,\"CompanyName         


        
相关标签:
4条回答
  • 2021-02-08 19:10

    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

    0 讨论(0)
  • 2021-02-08 19:23

    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.

    0 讨论(0)
  • 2021-02-08 19:26

    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.

    0 讨论(0)
  • 2021-02-08 19:34

    Sample Call

     Newtonsoft.Json.JsonConvert.SerializeObject(your_object,
       Newtonsoft.Json.Formatting.None, 
       new Newtonsoft.Json.JsonSerializerSettings 
       { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml })
    
    0 讨论(0)
提交回复
热议问题