将从服务端接收到的数据转成JSON数据

第一步,从服务端接收数据,并将数据转成int数组。

try{
                // 创建输入流对象InputStream
                is = socket.getInputStream();
                int length = is.available();
                // 创建一个数组,将is中的字节流输入到这个数组中
                int[] arr = new int[length];
                for(int i=0; i<length; i++){
                    arr[i] = is.read();
                }
                //将这次的数据和保存的数据加在一起
                if(arr_storage != null){
                    arr = add2intArray2oneArray(arr_storage, arr);
                }
                if(length > 0){
                    //writeLogToFile("有接收到来自服务端的信息");
                    detectionDataHead(arr);
                }
            }catch (Exception e){
                isRun = false;    //停止监听
                writeLogToFile("get Data is fail! " + e.toString());
            }

第二步,detectionDataHead(arr)里面是进行数据头的检查,具体的内容以后会添出来,里面有一个serverData2JsonObject的函数,用于将int数组转换成JSON对象。

private JSONObject serverData2JsonObject(int[] arr){
        /*
        对数组中第十一个元素以后的元素进行处理(前面10个是数据头)
        先将这些元素转换成字符串,然后再转换成JSONObject
        */
        char c;
        String string = "";
        JSONObject jsonObject = null;
        for(int i=10;i<arr.length;i++){
            c = (char)arr[i];
            string += c;
        }
        try {
            jsonObject = new JSONObject(string);
        }catch (JSONException e){
            writeLogToFile(e.toString());
        }
        return jsonObject;
    }

猜你喜欢

转载自blog.csdn.net/weixin_37378399/article/details/82318667
今日推荐