简体   繁体   中英

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.

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.

        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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM