Home » Java » java – Why Jackson JSON mapping exception when Serializing/Deserializing Geometry type-Exceptionshub

java – Why Jackson JSON mapping exception when Serializing/Deserializing Geometry type-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

When I create a User defined class “Asset”.

public class Asset {
    private UUID id;
    private String name;
}

And set an object of this class as a response.

@GetMapping("/testSerialization")
public Asset testSerialization() {
    return new Asset()
}

This controller works successfully.

But when the same controller uses Geometry Types the request fails,

import com.vividsolutions.jts.geom.Point;

// Does not work
@GetMapping("/testSerialization")
public Point testSerialization() {
    GeometryFactory geometryFactory = new GeometryFactory();
    Point point = geometryFactory.createPoint(new Coordinate(1, 2));
    return point;
}

I know that I have to add Serialization & De-Serialization references to Jackson, either manually or using a library like Jackson-datatype-jts, to enable Jackson to work with Geometry classes

My Question is, why do I have to do this explicitly for Geomtery types, whereas my Custom classes work without manipulating any configurations?

How to&Answers:

Jackson works well without any extra configuration with all regular POJO classes. Problem appears, when POJO classes are not regular: for example, do not have getters, setters, no-arg constructor, etc.

In your case, two or more classes have circular reference between them. When default serialiser wants to serialise all properties it dives in infinite recursion because of that. In that case we need to provide custom serialiser which handles this case properly.

This is why you need to provide custom serialisers and deserialisers for com.vividsolutions.jts.geom package.