读取json文件,并转换成jsonArray

读取json文件,并转换成jsonArray

public static JSONArray ConvertToJsonArray(String path, String pathType){

        JSONArray jsonArray =null;
        BufferedReader reader = null;
        StringBuilder jsonStrs = new StringBuilder();
        InputStream inputStream=null;
        try {
            //绝对路径
            if(pathType.equals(ABSOULUTE_PATH)){
                inputStream = new FileInputStream(path);
            }//相对路径
            else if(pathType.equals(RELATIVE_PATH)){
                inputStream=FileUtil.class.getResourceAsStream(path);
            }else{
                return jsonArray;
            }
            if(inputStream==null){
                logger.info(path+" is not exist or the json file is wrong");
                return jsonArray;
            }
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempStr = null;
            while ((tempStr = reader.readLine()) != null) {
                jsonStrs.append(tempStr);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info(jsonStrs.toString());
        try{
            jsonArray=JSONArray.parseArray(jsonStrs.toString().trim());
        }catch(IllegalStateException ex){
            logger.error(path+"JSON  File is wrong");
        }catch(JSONException ex){
            logger.error(path+"JSON  File is wrong");
        }
        return jsonArray;
    }

猜你喜欢

转载自blog.csdn.net/bwt1989/article/details/83280911
今日推荐