Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON not sending in UTF-8

Tags:

java

gson

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?

Response to client = data output 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);

    }
like image 778
William Falcon Avatar asked Jun 13 '13 02:06

William Falcon


1 Answers

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

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json = gson.toJson(objectToEncode);
like image 171
di0n0s Avatar answered Sep 20 '22 22:09

di0n0s