JSON character encoding

后端 未结 10 957
春和景丽
春和景丽 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条回答
  • The symptoms indicate that the JSON string which was originally in UTF-8 encoding was written to the HTTP response using ISO-8859-1 encoding and the webbrowser was instructed to display it as UTF-8. If it was written using UTF-8 and displayed as ISO-8859-1, then you would have seen aériennes. If it was written and displayed using ISO-8859-1, then you would have seen a�riennes.

    To fix the problem of the JSON string incorrectly been written as ISO-8859-1, you need to configure your webapp / Spring to use UTF-8 as HTTP response encoding. Basically, it should be doing the following under the covers:

    response.setCharacterEncoding("UTF-8");
    

    Don't change your content type header. It's perfectly fine for JSON and it is been displayed as UTF-8.

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

    finally I got the solution:

    Only put this line

    @RequestMapping(value = "/YOUR_URL_Name",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    

    this will definitely help.

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

    If you're using StringEntity try this, using your choice of character encoding. It handles foreign characters as well.

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

    If the suggested solutions above didn't solve your issue (as for me), this could also help:

    My problem was that I was returning a json string in my response using Springs @ResponseBody. If you're doing this as well this might help.

    Add the following bean to your dispatcher servlet.

    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/plain;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
    

    (Found here: http://forum.spring.io/forum/spring-projects/web/74209-responsebody-and-utf-8)

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