读取geojson的文件数据并将json数据转换成json对象,再按条件插入到postgresql数据库中
需求:
需要在表中加上一个geojson字段,该字段存json字符,最终从数据库表中查出一个geojson格式的字符返回给前端,前端去做聚合处理。
一:准备一份geojson的文件test001.geojson(该文件有3000多行,对应表中3000多条数据)
该文件的特点每一行都是一个json格式的数据,每一行的最后会有逗号(最后一行不含有),读取文件需要处理掉逗号。
二:编写代码(用JSONObject将json字符串转换成json对象 )
1.添加依赖:
<dependency>
<groupId>org.kopitubruk.util</groupId>
<artifactId>JSONUtil</artifactId>
<version>1.1.1</version>
</dependency>
2.编写读写文件的代码:
@RequestMapping("/addDate")
public void addDate() throws IOException{
List<String> list = new ArrayList<String>();
FileInputStream fis = new FileInputStream("E:\\qgis\\test001.geojson");
// 防止路径乱码 如果utf-8 乱码 改GBK eclipse里创建的txt 用UTF-8,在电脑上自己创建的txt 用GBK
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = "";
JSONObject json,propertiesJson;
String geometry;
while ((line = br.readLine()) != null) {
//list.add(line);
// 每行小于100或者为空的跳过
if(line==null || line.length()<100)
continue;
//在最后一行添加逗号
if(line.endsWith(","))
//将每行的逗号去除
line = line.substring(0,line.length()-1);
//System.out.println("---==="+line);
//将每行的数据转换成json格式
json = JSONObject.parseObject(line);
if(json == null)continue;
//获取key为properties的数据
propertiesJson = json.getJSONObject("properties");
if(propertiesJson == null)continue;
//获取key为geometry的数据,geometry里面的元素本身就是json的格式,数据直接以json的形式存入数据库中。
geometry = json.getString("geometry");
Map<String, Object> map = new HashMap();
//再获取
map.put("pid", propertiesJson.get("pid"));
map.put("geometry", geometry);
System.out.println("---"+map);
updateGeoJson(map);
//break;
}
br.close();
isr.close();
fis.close();
}
private void updateGeoJson(Map<String, Object> map) {
String sql = "update test1_copy set geojson='"+map.get("geometry")+"' where pid="+map.get("pid") ;
jdbc.update(sql);
}