Java 读取 json文件

public ResponseBean getAreas() {
        String path = getClass().getClassLoader().getResource("area.json").toString();
        path = path.replace("\", "/");
        if (path.contains(":")) {
            //path = path.substring(6);// 1
         path = path.replace("file:/","");// 2
        }
        JSONArray jsonArray = null;
        try {
            String input = FileUtils.readFileToString(new File(path), "UTF-8");
            JSONObject jsonObject = JSONObject.fromObject(input);
            if (jsonObject != null) {
                jsonArray = jsonObject.getJSONArray("list");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonArray = null;
        }
        return new ResponseBean(jsonArray);
    }

 area.json文件放入resources资源目录中

ps

this.getClass().getResource("")

和this.getClass().getClassloader().getResource("") 区别??

第一个是类路径下(即 class 根目录)

第二个目录是 class目录里面当前类的包路径

原文地址:https://www.cnblogs.com/ydymz/p/8821287.html