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目錄里面當前類的包路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM