依赖:
<dependencies>
<!-- geojson -->
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-geojson</artifactId>
<version>27.2</version>
</dependency>
<!-- No code "EPSG:4490" from authority "EPSG" found for object of type "EngineeringCRS" -->
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>27.2</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>osgeo-release</id>
<name>Open Source Geospatial Foundation Repository</name>
<url>https://repo.osgeo.org/repository/release/</url>
</repository>
<repository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>boundless</id>
<name>Boundless Maven Repository</name>
<url>https://repo.boundlessgeo.com/main/</url>
</repository>
<repository>
<id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url>
</repository>
</repositories>
1. GeoJson字符串读取
1)通过FeatureJSON实例解析
可能存在问题:要素的属性字段若包含嵌套类型,无法解析嵌套类型,且无法解析之后的要素属性
FeatureCollection featureCollection = new FeatureJSON().readFeatureCollection(str);
2) 通过GeoJSONReader解析要素集
参考 (11条消息) GeoTools解析GeoJson为要素集(FeatureCollection)含嵌套数组属性_billy_gisboy的博客-CSDN博客
2. 将 FeatureCollection 对象转换成 geoJson 字符串
/**
* 将 FeatureCollection 对象转换成 geoJson 字符串
*
* @param featureCollection FeatureCollection 或其子类
* @return geoJson字符串
*/
public static String featureCollection2GeoJsonStr(FeatureCollection featureCollection) throws IOException {
// 精度控制小数点后的小数位数
FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(8));
// 输出坐标系
featureJSON.setEncodeFeatureCollectionCRS(true);
// 值为null的属性也识别
// featureJSON.setEncodeNullValues(true);
return featureJSON.toString(featureCollection);
}
3. 设置坐标系信息
需要导入依赖
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>27.2</version>
</dependency>
// 设置坐标系信息,仅设置了坐标系,并不改变坐标
// longitudeFirst:true 经度在前
featureCollection = new ForceCoordinateSystemFeatureResults(featureCollection, CRS.decode("EPSG:4326", true), true);