java – JSON sent by Socket error


When the JSON String is too large, part of the String is lost on submission. I'm sending it like this:

private void btComunicarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        List<PessoaMOD> pessoas = new ArrayList<PessoaMOD>();

        for (int i = 1; i <= 2000; i++) {
            pessoas.add(new PessoaMOD(i, "Pessoa " + i));

        try {
            Socket cliente = new Socket("", 12345);
            enviarMensagem(codificarListarDiretorio(pessoas), cliente);
        } catch (Exception e) {
            System.out.println("Erro: " + e.getMessage());
        } finally {

public ByteArrayOutputStream codificarListarDiretorio(List<PessoaMOD> pessoas) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        Gson gson = new GsonBuilder().create();
        return bos;

public void enviarMensagem(ByteArrayOutputStream mensagem, Socket socket) throws IOException {
        byte[] msg = mensagem.toByteArray();
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        out.writeInt(msg.length); //O tamanho da mensagem
        out.write(msg); //Os dados

and I get it on the server like this:

int tamanhoMsg = entrada.readInt();                   
byte[] bufferJson = new byte[tamanhoMsg];, 0, bufferJson.length);
String json = new String(bufferJson);

But Json's String isn't complete when it's too big.

What happens is that the number of bytes is larger than the length supports, so the message size doesn't send complete.

I also tried sending via the writeUTF() method;

But as the String is big, it generates this error: encoded string too long: 677789 bytes


Try to change the JSON reading part of your code on the server from DataInputStream to BufferedReader :

// ...
long tamanhoMsg = entrada.readLong();

BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            // guava library - limita a leitura de um input stream
                inputStream,                // input stream do socket
                tamanhoMsg                  // tamanho máximo a ser lido do input stream

JsonObject data = JsonParser.parse(reader)  // le o reader convertendo para  json
        getAsJsonObject();                  // retorna como JsonObject

// ...

You could also change the message length information from int to long.

Scroll to Top