jersey web service json utf-8 encoding

后端 未结 7 2009
执笔经年
执笔经年 2020-12-08 00:28

I made a small Rest webservice using Jersey 1.11. When i call the url that returns Json, there are problems with the character encoding for non english characters. The corre

相关标签:
7条回答
  • 2020-12-08 00:49

    if @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") does not function, then try:

    @Produces("application/json;charset=utf-8")

    in theory it is the same, but the first option did not work to me

    0 讨论(0)
  • 2020-12-08 00:57

    If adding the charset to each and every resource is not an option, maybe the answer to this question, which shows how to enforce a default charset, might be helpful.

    0 讨论(0)
  • 2020-12-08 00:57

    i got the same issue in servlet

    kindly use : resp.setContentType("application/json;charset=utf-8");

    public static void flashOutput(HttpServletRequest req
                , HttpServletResponse resp
                , String output) {
    
            try {
    
                Utils.print2("output flash"+output);
    
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter pw = resp.getWriter();
                pw.write( new String(output.getBytes("UTF-8")));
                pw.close();
                resp.flushBuffer();
    
            } catch (Exception e) {
                // TODO: handle exception
            }
    
        }// end flashOutput
    
    0 讨论(0)
  • 2020-12-08 00:58

    Jersey should always produce utf-8 by default, sounds like the problem is that your client isn't interpreting it correctly (the xml declaration doesn't "make" it utf-8, just tells the client how to parse it).

    What client are you seeing these problems with?

    Valid JSON is only supposed to be Unicode (utf-8/16/32); parsers should be able to detect the encoding automatically (of course, some don't), so there is no encoding declaration in JSON.

    You can add it to the Content-Type like so:

    @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
    
    0 讨论(0)
  • 2020-12-08 01:03

    responseMessage is bean class in which we can send UTF-8 charset in response.

    return Response.ok(responseMessage).header("Content-Type", "application/json;charset=UTF-8").build();
    
    0 讨论(0)
  • 2020-12-08 01:06

    Jersey is buggy, when Content-Type application/json is used, it does not detect the unicode JSON encoding automatically as it suppose to, but deserialize the request body with whatever runtime platform encoding is used by you server. Same applies for the response body serialization.

    Your client need to explicitly specify UTF-8 charset:

    Content-Type: application/json;charset=utf-8
    
    0 讨论(0)
提交回复
热议问题