Java 读取 json文件

getResource("")这个方法可以用于查看当前目录
得到的路径中(file:/E:/Program%20Files/works/source/trunk/glory/mars/build/classes/artifacts/app/exploded/app-1.0-SNAPSHOT.war/WEB-INF/classes/area.json)
包含“file:/”需要手动去掉;而且要注意文件目录不能有空格,否则:E:/Program%20Files 是找不到文件目录的;
this.getClass().getResource("")
和this.getClass().getClassloader().getResource("") 区别??
第一个是类路径下(即 class 根目录)
第二个目录是 class目录里面当前类的包路径;
参考下图

得到推荐写法:

this.getClass().getClassLoader().getResource("文件名.文件类型")

 1 public ResponseBean getAreas() {
 2         String path = getClass().getClassLoader().getResource("area.json").toString();
 3         path = path.replace("\\", "/");
 4         if (path.contains(":")) {
 5             //path = path.substring(6);// 1
         path = path.replace("file:/","");// 2
6 } 7 JSONArray jsonArray = null; 8 try { 9 String input = FileUtils.readFileToString(new File(path), "UTF-8"); 10 JSONObject jsonObject = JSONObject.fromObject(input); 11 if (jsonObject != null) { 12 jsonArray = jsonObject.getJSONArray("list"); 13 } 14 } catch (Exception e) { 15 e.printStackTrace(); 16 jsonArray = null; 17 } 18 return new ResponseBean(jsonArray); 19 }

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

area.json数据如下(参考)

{"list":[{"全国":[{"id":0,"title":"全国"}]},{"华东":[{"id":31892,"title":"上海"},{"id":32556,"title":"山东"},{"id":31913,"title":"江苏"},{"id":32054,"title":"浙江"},{"id":32170,"title":"安徽"},{"id":32430,"title":"江西"}]},{"华南":[{"id":32325,"title":"福建"},{"id":33543,"title":"海南"},{"id":33224,"title":"广东"},{"id":34669,"title":"台湾"},{"id":34689,"title":"香港"},{"id":34691,"title":"澳门"}]},{"华北":[{"id":31002,"title":"北京"},{"id":31022,"title":"天津"},{"id":31043,"title":"河北"},{"id":31244,"title":"山西"},{"id":31387,"title":"内蒙古"}]},{"华中":[{"id":31043,"title":"河北"},{"id":32737,"title":"河南"},{"id":32939,"title":"湖北"},{"id":33071,"title":"湖南"}]},{"东北":[{"id":31516,"title":"辽宁"},{"id":31649,"title":"吉林"},{"id":31733,"title":"黑龙江"}]},{"西北":[{"id":34199,"title":"陕西"},{"id":34508,"title":"宁夏"},{"id":34329,"title":"甘肃"},{"id":34444,"title":"青海"},{"id":34541,"title":"新疆"}]},{"西南":[{"id":33400,"title":"广西"},{"id":33613,"title":"四川"},{"id":33839,"title":"贵州"},{"id":33947,"title":"云南"},{"id":34110,"title":"西藏"},{"id":33569,"title":"重庆"}]}]}

  

posted @ 2017-04-18 11:18  戴眼镜的蚂蚁  阅读(51823)  评论(0编辑  收藏  举报