使用 JTS jackson 时更改经纬度轴

Change the axis of lat long when using JTS jackson

我在 spring 引导中使用 locationtech JTS 库,使用 jackson 作为 json 序列化器和支持序列化 JTS 的 Jts 数据类型模块 geometry.The 我面临的问题是返回 json 时坐标的轴顺序是 long lat 而不是 lat long 在 Whosebug 上有一个解决方案我想知道是否有任何其他方法可以实现此功能而不是始终应用​​ InvertCoordinateFilter每当我创建一个功能。 下面是我正在使用的代码

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JtsModule());


    double lat  = 32.3456789;
    double lng = 72.423434;

    GeometryFactory gf = new GeometryFactory();
    Point point = gf.createPoint(new Coordinate(lng,lat ));
    String json = mapper.writeValueAsString(point);
    System.out.println(json);

输出为

{"type":"Point","coordinates":[72.423434,32.3456789]}

我希望输出为

{"type":"Point","coordinates":[32.3456789,72.423434]}

无法调整 GeometrySerializer, since the order is hardcoded in lines 174-175

为了避免自己编写序列化程序,您可以复制 GeometrySerializer 并将这两行反转,但您实际上不会使用官方的 jts-data-type,并且将来会修改除非您手动执行,否则库不会反映在您复制的序列化程序中。

或者,只需修饰 GeometrySerializer 并在调用它之前使用 InverseCoordinateFilter

public static class CustomGeometrySerializer extends JsonSerializer<Geometry> {
  private GeometrySerializer innerSerializer;
  private InvertCoordinateFilter inverter = new InvertCoordinateFilter();

  public CustomGeometrySerializer() {
    this(new GeometrySerializer());
  }

  public CustomGeometrySerializer(GeometrySerializer innerSerializer) {
    this.innerSerializer = innerSerializer;
  }

  @Override
  public void serialize(Geometry value, JsonGenerator jgen,
      SerializerProvider provider) throws IOException {

    // Create a new Geometry to avoid mutating the original one
    Geometry newValue = value.copy();
    newValue.apply(inverter);
    innerSerializer.serialize(newValue, jgen, provider);
  }

  private static class InvertCoordinateFilter implements CoordinateFilter {
    public void filter(Coordinate coord) {
      double oldX = coord.x;
      coord.x = coord.y;
      coord.y = oldX;
    }
  }
}

现在,不用注册 JtsModule,而是使用反序列化器自己创建一个模块:

ObjectMapper mapper = new ObjectMapper();

SimpleModule inverseJtsModule = new SimpleModule();
inverseJtsModule.addSerializer(Geometry.class, new CustomGeometrySerializer());
mapper.registerModule(inverseJtsModule);

double lat  = 32.3456789;
double lng = 72.423434;

GeometryFactory gf = new GeometryFactory();
Point point = gf.createPoint(new Coordinate(lng, lat));
String json = mapper.writeValueAsString(point);
System.out.println(json);

您现在可以安全地序列化您的几何图形,而无需显式反转每个几何图形。对于反序列化,您可以使用相同的方法,装饰 GeometryDeserializer.