Yige Song
Yige Song

Reputation: 373

Java: JSON.simple Parser - convert BufferedReader's readUTF string to Reader

I am writing a server which receives a JSON string then parse it to Java JSONObject, by using the JSON.simple package: https://mkyong.com/java/json-simple-example-read-and-write-json/.

I am using DataInputStream to read input, but when I try to parse the input by writing:

JSONObject json = (JSONObject) parser.parse(input.readUTF());

it says that parse(Java.io.Reader) can not be applied to (Java.lang.String). SO how do I convert the input.readUTF()into the required reader format?

For reference, my code for receiving and parsing the JSON input:

    public class ReceiveThread implements Runnable{
        private DataInputStream input;

        public ReceiveThread(DataInputStream input){
            this.input = input;
        }

        @Override
        public void run() {
            JSONParser parser = new JSONParser();
            while (true){
                String res = null;
                try {
                    if (input.available() > 0){
                        JSONObject json = (JSONObject) parser.parse(input.readUTF());
                        System.out.println("Server response: "+ res);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.exit(-1);
                }
            }
        }
    }

At the client side, I send the JSON file by:

    public class SendThread implements Runnable{
        private DataOutputStream output;

        public SendThread(DataOutputStream output){
            this.output = output;
        }

        @Override
        public void run() {
            // create json string
            JSONObject json = new JSONObject();
            json.put("key1", 1);
            json.put("key2", "Helloworld");

            try {
                this.output.writeUTF(json.toString());
                this.output.flush();
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

Thanks in advance! Any bits of help is appreciated.

Yige

Upvotes: 0

Views: 245

Answers (1)

Yige Song
Yige Song

Reputation: 373

It turns out to be the version problem with JSON.simple.

In v1.1, the parse method takes the reader argument, but in version 1.1.1 parse is able to take String arguments.

Upvotes: 0

Related Questions