JSON character encoding

后端 未结 10 956
春和景丽
春和景丽 2020-11-27 14:14

My Java web application submits an AJAX request that returns JSON such:

{\'value\': \'aériennes\'}

When \'aériennes\' is displayed in the w

相关标签:
10条回答
  • 2020-11-27 14:55

    The answers here helped me solve my problem, although it's not completely related. I use the javax.ws.rs API and the @Produces and @Consumes annotations and had this same problem - the JSON I was returning in the webservice was not in UTF-8. I solved it with the following annotations on top of my controller functions :

    @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON + "; charset=UTF-8")
    

    and

    @Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON + "; charset=UTF-8")
    

    On every endpoint's get and post function. I wasn't setting the charset and this solved it. This is part of jersey so maybe you'll have to add a maven dependency.

    0 讨论(0)
  • 2020-11-27 14:57
    response.setContentType("application/json;charset=utf-8");
    
    0 讨论(0)
  • 2020-11-27 15:01

    Also, you can use spring annotation RequestMapping above controller class for receveing application/json;utf-8 in all responses

    @Controller
    @RequestMapping(produces = {"application/json; charset=UTF-8","*/*;charset=UTF-8"})
    public class MyController{
     ...
    }
    
    0 讨论(0)
  • 2020-11-27 15:03

    I don´t know if this is relevant anymore, but I fixed it with the @RequestMapping annotation.

    @RequestMapping(method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    
    0 讨论(0)
  • 2020-11-27 15:05

    First, your posted data isn't valid JSON. This would be:

    {"value": "aériennes"}
    

    Note the double quotes: They are required.

    The Content-Type for JSON data should be application/json. The actual JSON data (what we have above) should be encoded using UTF-8, UTF-16, or UTF-32 - I'd recommend using UTF-8.

    You can use a tool like Wireshark to monitor network traffic and see how the data looks, you should see the bytes c3 89 for the é. I've never worked with Spring, but if it's doing the JSON encoding, this is probably taken care of properly, for you.

    Once the JSON reaches the browser, it should good, if it is valid. However, how are you inserting the data from the JSON response into the webpage?

    0 讨论(0)
  • 2020-11-27 15:07

    That happened to me exactly the same with this:

    <%@ page language="java" contentType="application/json" pageEncoding="UTF-8"%>
    

    But this works for me:

    <%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%>
    

    Try adding

     ;charset=UTF-8
    

    to your contentType.

    0 讨论(0)
提交回复
热议问题