Bob
Bob

Reputation: 10815

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.

Upvotes: 6

Views: 12202

Answers (2)

Nomesh Gajare
Nomesh Gajare

Reputation: 855

        StringBuffer buffer = new StringBuffer();
        int ch;
        boolean run = true;
        try {
            while(run) {
                ch = reader.read();
                if(ch == -1) { break; }
                buffer.append((char) ch);
                if(isJSONValid(buffer.toString())){ run = false;}
            }
        } catch (SocketTimeoutException e) {
            //handle exception
        }



private boolean isJSONValid(String test) {
        try {
            new JSONObject(test);
        } catch (JSONException ex) {
            try {
                new JSONArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }

        return true;
    }

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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.

Upvotes: 6

Related Questions