Jackson deserialize GeoJson Point in Spring Boot

前端 未结 3 1832
日久生厌
日久生厌 2020-12-18 06:27

I have a @Entity model that has a property of type com.vividsolutions.jts.geom.Point. When I try to render this model in a @RestController

3条回答
  •  醉酒成梦
    2020-12-18 06:53

    As of 2020 most of the JTS libraries are outdated and no longer work. I found one fork on Maven Central that was updated recently and it worked flawlessly with jackson-core:2.10.0 and jts-core:1.16.1:

    implementation 'org.n52.jackson:jackson-datatype-jts:1.2.4'

    Sample usage:

        @Test
        void testJson() throws IOException {
    
            var objectMapper = new ObjectMapper();
            objectMapper.registerModule(new JtsModule());
    
            GeometryFactory gf = new GeometryFactory();
            Point point = gf.createPoint(new Coordinate(1.2345678, 2.3456789));
    
            String geojson = objectMapper.writeValueAsString(point);
    
            InputStream targetStream = new ByteArrayInputStream(geojson.getBytes());
            Point point2 = objectMapper.readValue(targetStream, Point.class);
    
            assertEquals(point, point2);
        }
    

    You don't need to use any annotations on class fields or register new Spring Beans, just register the JTS module with Jackson.

提交回复
热议问题