GSON not sending in UTF-8

前端 未结 3 727
心在旅途
心在旅途 2021-02-08 17:10

The following method sends a JSON reply. However on the receiving end I keep getting invalid characters, and UTF-8 isn\'t decoding the data. What am I doing wrong?

相关标签:
3条回答
  • 2021-02-08 17:44

    I have no idea why you would write your own HTTP protocol code. It's a lot like writing your own XML parser: No matter how good a programmer you are, you are bound to get it wrong.

    Anyway, as the DataOutputStream documentation states, doing writeBytes on a String will just discard its high eight bits. So what you get is... something, but not UTF8. What you should do is:

    String jsonString = new Gson().toJson(objectToEncode);
    byte[] utf8JsonString = jsonString.getBytes("UTF8");
    responseToClient.write(utf8JsonString, 0, utf8JsonString.Length);
    
    0 讨论(0)
  • 2021-02-08 18:08

    The first solution didn't work for me, I did this:

    Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    String json = gson.toJson(objectToEncode);
    
    0 讨论(0)
  • 2021-02-08 18:08

    Use the following code to encode

     response.setCharacterEncoding("UTF8"); // this line solves the problem
     response.setContentType("application/json");
    
    0 讨论(0)
提交回复
热议问题