GSON does not send to UTF-8

The following method sends a JSON response. However, on the receiving side, I continue to receive invalid characters, and UTF-8 does not decode the data. What am I doing wrong?

Response to client stream = data stream

//Get the client request clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream())); //connectedclient = socket //Start response object responseToClient = new DataOutputStream(connectedClient.getOutputStream()); /** * Sends a JSON response for an object * @param objectToEncode * @throws Exception */ private void sendJSONResponse(Object objectToEncode) throws Exception{ //Encode object into JSON String jsonString = new Gson().toJson(objectToEncode); // HTTP Header... Status code, last modified responseToClient.writeBytes(HTTP_OK_STATUS_CODE); responseToClient.writeBytes(CONTENT_TYPE_JSON); responseToClient.writeBytes("Last-modified: "+ HelperMethods.now() +" \r\n"); responseToClient.writeBytes("\r\n"); // The HTTP content starts here responseToClient.writeBytes(jsonString); } 
+8
java gson
source share
2 answers

I have no idea why you should write your own HTTP protocol code. This is very similar to writing your own XML parser: no matter how good you are as a programmer, you must make mistakes.

In any case, as indicated in the DataOutputStream documentation, executing writeBytes on a String will simply override its eight bits. So you get ... something, but not UTF8. What you need to do:

 String jsonString = new Gson().toJson(objectToEncode); byte[] utf8JsonString = jsonString.getBytes("UTF8"); responseToClient.write(utf8JsonString, 0, utf8JsonString.Length); 
+15
source share

Use the following code to encode

  response.setCharacterEncoding("UTF8"); // this line solves the problem response.setContentType("application/json"); 
0
source share

All Articles