读取本地json文件

    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String path = Objects.requireNonNull(AppTestController.class.getClassLoader().getResource("xx.json")).getPath();
        String s = readJsonFile(path);
        JSONObject jobj = JSON.parseObject(s);
        JSONArray movies = jobj.getJSONArray("RECORDS");//构建JSONArray数组
        for (int i = 0; i < movies.size(); i++) {
            JSONObject key = (JSONObject) movies.get(i);
            String name = (String) key.get("name");
            System.out.println(name);
         
        }
    }

你可能感兴趣的:(读取本地json文件)