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.
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.
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.
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.
InputStream inputStreamObject = PositionKeeperRequestTest. class. getResourceAsStream(jsonFileName); BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With