Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 953
Bob Avatar asked Oct 09 '14 17:10

Bob


People also ask

How do I read a JSON stream?

JsonReader. JsonReader is an input reader that can read a JSON stream. It can be created using a Reader object as demonstrated in this code or using a File corresponding to the JSON stream. The main method in this class is the JsonReader.

How to read JSON file using InputStream in Java?

First we start by getting the InputStream of the JSON file to be read using getResourceAsStream() method. Next we construct a JSONTokener from the input stream and create an instance of JSONObject to read the JSON entries.

How to read JSON file in Java?

The json. simple is a lightweight JSON processing library that can be used to read and write JSON files and it can be used to encode or decode JSON text and fully compliant with JSON specification (RFC4627). In order to read a JSON file, we need to download the json-simple. jar file and set the path to execute it.

How to create JSON Object from InputStream in Java?

InputStream inputStreamObject = PositionKeeperRequestTest. class. getResourceAsStream(jsonFileName); BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.


1 Answers

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.

like image 190
Luiggi Mendoza Avatar answered Sep 18 '22 14:09

Luiggi Mendoza