张洋洋
2025-01-13 07b0c2b723f16d88c64a0e9151fdbef81a0a8a74
src/main/java/com/se/simu/utils/ShpReadUtils.java
@@ -1,5 +1,10 @@
package com.se.simu.utils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
@@ -13,15 +18,24 @@
import org.opengis.feature.simple.SimpleFeatureType;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
public class ShpReadUtils {
    public static void main(String[] args) throws Exception {
        readPointShp("D:\\城市内涝\\sem\\管点\\pipeline-point.shp");
        //readPointShp("D:\\城市内涝\\sem\\管线\\pipeline-conduit.shp");
        //readPointShp("D:\\城市内涝\\sem\\管点\\pipeline-point.shp");
        readPointShp("D:\\城市内涝\\sem\\管线\\pipeline-conduit.shp");
    }
    static class GeometrySerializer extends JsonSerializer<Geometry> {
        @Override
        public void serialize(Geometry value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeStartObject();
            gen.writeStringField("type", value.getGeometryType());
            gen.writeObjectField("coordinates", value.getCoordinates());
            gen.writeEndObject();
        }
    }
    /**
     * @param url shp文件路径
     * @return shp解析后的内容
@@ -30,7 +44,8 @@
    public static List<Map<String, Object>>  readPointShp(String url) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        File file = new File(url);
        map.put("url", file.toURI().toURL());// 必须是URL类型
        map.put("url", file.toURI().toURL());
        // 必须是URL类型
        DataStore dataStore = DataStoreFinder.getDataStore(map);
        //字符转码,防止中文乱码
        ((ShapefileDataStore) dataStore).setCharset(Charset.forName("utf8"));
@@ -49,7 +64,12 @@
                Property property = iterator.next();
                if ("the_geom".equals(property.getName().toString())) {
                    Geometry geometry = reader.read(property.getValue().toString());
                    objectMap.put(property.getName().toString(), geometry);
                    SimpleModule module = new SimpleModule();
                    module.addSerializer(Geometry.class, new GeometrySerializer());
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(module);
                    String jsonString = mapper.writeValueAsString(geometry);
                    objectMap.put(property.getName().toString(), jsonString);
                } else {
                    objectMap.put(property.getName().toString(), property.getValue());
                }