Geometry from vividsolutions JTS fails when creating JSON

前端 未结 2 1179
逝去的感伤
逝去的感伤 2021-02-19 00:56

pals. I\'m using vividsolutions\'s library JTS (1.13) for Points and Polygons in my application, but when I try to convert geometry objects into JSON, my application fails. Ther

2条回答
  •  失恋的感觉
    2021-02-19 01:58

    This is not very nice solution, but it helps me to solve issue.

    So, issue is in Jackson way to serialize JTS Polygon and Point objects. This issue is solved by project jackson-datatype-jts. You can show this library sources on github - https://github.com/bedatadriven/jackson-datatype-jts

    All I need to run my test_point is:

    1) Add dependency and repository for jackson-datatype-jts:

    
        
            com.bedatadriven
            jackson-datatype-jts
            1.0-SNAPSHOT
        
    
    
    
    
        
            sonatype-oss
            https://oss.sonatype.org/content/groups/public
        
    
    

    2) Change source code this way:

    @RequestMapping(value = "/test_point", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Point testPoint() {
    
        Point point =geometryFactory.createPoint(new Coordinate(37.77, 60.01));
        String result = "";
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JtsModule());
        try {
            result = objectMapper.writeValueAsString(point);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    
        return point;
    }
    

    And this really works, but what is I want to return point in my other POJO? There is solution for Spring Framework: 1) Repeat step 1 from previous section 2) Create a class extending ObjectMapper Class:

    public class CustomMapper extends ObjectMapper {
    
    public CustomMapper() {
        super();
        this.registerModule(new JtsModule());
    }
    }
    

    3) Edit your spring config xml (for me - servlet.xml) add next strings:

    
            
                
                
                
                    
                
            
        
    
        
    

    Now your ObjectMapper instance is substituted with your Custom Object mapper realization. An it works!

提交回复
热议问题