Search code examples
javajsontcpinputstream

Java read JSON input stream


I am programming a simple TCP server in Java that is listening on some URL on some port. Some client (not in Java) sends a JSON message to the server, something like this {'message':'hello world!', 'test':555}. I accept the message an try to get the JSON (I am thinking to use GSON library).

Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();

But how can I get the message from input stream? I tried to use ObjectInputStream, but as far as I understood it waits serialized data and JSON is no serialized.


Solution

  • Wrap it with a BufferedReader and start reading the data from it:

    StringBuilder sb = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
        String line;
        while ( (line = br.readLine()) != null) {
            sb.append(line).append(System.lineSeparator());
        }
        String content = sb.toString();
        //as example, you can see the content in console output
        System.out.println(content);
    }
    

    Once you have it as a String, parse it with a library like Gson or Jackson.