Home » Java » In java tcp how to convert json+binary data?

In java tcp how to convert json+binary data?

Posted by: admin August 11, 2018 Leave a comment


I’m going to convert the received data from socket.inputStream like this:

{ "ID":123,"PICData":{"ID":"100", "PackageIndex":3, "Length":1234, "TotalLength":4321}}\r\n binary data

as you can see the data not always binary data , a JSON string is behind the data,
so how can I read the json to string value and binary data to byte[]?

I try to use readline() and convert to byte array but it always return more data than I should received.

here is what i do:

this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    public void run() {
        try {
            String line = null;
            while ((line = this.bufferedReader.readLine()) != null) {
                handleReceivedMessage(line, mFileSendListener);
        } catch (Exception e) {
            LogController.i(TAG, "tcp read ex:" + e.toString());
private void handleReceivedMessage(String receiveMsg, DataSendListener listener) {
        try {
            //is json data
            jsonObject = new JSONObject(receiveMsg);
            LogController.d(TAG, "handleReceivedMessage: " + receiveMsg);
            JSONObject picObdject = jsonObject.optJSONObject("PCMData");
            length = picObdject.optInt("Length");
            totalLength = picObdject.optInt("TotalLength");
            Log.d(TAG, "handleReceivedMessage: json=========================");
            //reset stream
        } catch (Exception e) {
            //is binary data
            int byteSize = receiveMsg.getBytes().length;
            Log.d(TAG, "byteSize========" + byteSize);
            byteArrayOutputStream.write(receiveMsg.getBytes(), 0, byteSize);
            Log.d(TAG, "byteArrayOutputStream.size: " + byteArrayOutputStream.size() + "Length ====" + length + "TotalLength====" + totalLength);
            if (byteArrayOutputStream.size() == length) {
                //when byteArrayOutputStream.size() equals length notify the data
                // convert json and data over notify
                notifyMessageReceived(jsonObject.toString(), byteArrayOutputStream.toByteArray());


log show my byteArrayOutputStream.size() not equals length

here is the log:

tcp received log