fastJson依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
String s = JSON.toJSONString(obj);
JSONObject json= JSON.parseObject(geoJson);
Object where = json.get("name");
/**
* 解析单个feature的geojson
* @param geojson
* @param geoSRS
* @return
* @throws IOException
* @throws FactoryException
*/
public static SimpleFeature jsonToFeature(String geojson,String geoSRS) throws IOException, FactoryException {
//设置精度为15位
FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(2));
SimpleFeature simpleFeature = featureJSON.readFeature(geojson);
//解决geojson的geometry定义的问题
SimpleFeatureType newType = retype(simpleFeature.getFeatureType(),geoSRS);
SimpleFeature newFeature = retypeFeature(simpleFeature,newType);
return newFeature;
}
/**
* 解析多个feature的geojson
* @param geojson
* @param geoSRS
* @return
* @throws IOException
* @throws FactoryException
* @throws SchemaException
*/
public static FeatureCollection jsonToCollection(String geojson,String geoSRS) throws IOException, FactoryException, SchemaException {
//设置精度为15位
FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(2));
// 读取为FeatureCollection
FeatureCollection featureCollection = featureJSON.readFeatureCollection(geojson);
// 获取SimpleFeatureType
SimpleFeatureType simpleFeatureType = (SimpleFeatureType) featureCollection.getSchema();
String srs = null;
//如果有坐标系,转换坐标系的经纬度
if(geoSRS != null){
srs = geoSRS;
} else if(simpleFeatureType.getCoordinateReferenceSystem() != null) {
srs = CRS.lookupIdentifier(simpleFeatureType.getCoordinateReferenceSystem(),true);
featureCollection = new ForceCoordinateSystemFeatureResults(featureCollection, CRS.decode(srs, true));
}
//解决geojson的geometry定义的问题
SimpleFeatureType newType = retype(simpleFeatureType,geoSRS);
//变换feature的type
FeatureCollection listFeatureCollection = new ListFeatureCollection(newType);
SimpleFeatureIterator iterator = (SimpleFeatureIterator) featureCollection.features();
while (iterator.hasNext()){
SimpleFeature newFeature = retypeFeature(iterator.next(),newType);
((ListFeatureCollection)listFeatureCollection).add(newFeature);
}
iterator.close();
listFeatureCollection=new ForceCoordinateSystemFeatureResults(listFeatureCollection, CRS.decode(srs, true));
return listFeatureCollection;
}
public static String FeatureToJson(SimpleFeature simpleFeature) throws IOException {
FeatureJSON featureJSON=new FeatureJSON();
return featureJSON.toString(simpleFeature);
}
public static String FeatureCollectionToJson(SimpleFeatureCollection collection) throws IOException {
FeatureJSON featureJSON=new FeatureJSON();
return featureJSON.toString(collection);
}