首页 > 代码库 > Java读写geojson

Java读写geojson

/** 读 **/
public Map<Integer, SiteEntity> getSiteMap() {
        Map<Integer, SiteEntity> map = new HashMap<Integer, SiteEntity>();
        URL dataUrl = this.getClass().getClassLoader().getResource("public\\station.json");  //  259
        try{
            BufferedReader br =new BufferedReader(new FileReader(new File(dataUrl.toURI())));
            String s = null;
            while((s = br.readLine()) != null){  // s 为原生的json串
//                System.out.println("00=="+s);
                JSONObject jo = new JSONObject(s); // 创建一个包含原始json串的json对象
                JSONArray features = jo.getJSONArray("features"); //找到features的json数组
                for (int i = 0; i < features.length(); i++) {
                    SiteEntity siteEntity = new SiteEntity();
                    JSONObject info = features.getJSONObject(i); // 获得features的第i个对象

                    JSONObject geometry = info.getJSONObject("geometry");
                    JSONObject properties = info.getJSONObject("properties");

                    siteEntity.setSite_stano(properties.getString("stano"));  // 获得站名

                    List list  = geometry.getJSONArray("coordinates").toList();  // 获得经纬度
                    siteEntity.setSite_longitude(Double.parseDouble(list.get(0).toString()));
                    siteEntity.setSite_latitude(Double.parseDouble(list.get(1).toString()));
//                    System.out.println(siteEntity.getSite_longitude()+"\n"+siteEntity.getSite_latitude());
                    map.put(i,siteEntity);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }


/**写**/
public void jsonOutPut(Map map) {
        ObjectMapper mapper = new ObjectMapper();
        try{
            mapper.writeValue(new File("D:/river-site.json"), map);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

 

Java读写geojson