2

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?

  • Can you post how does you Point class looks like? – Mritunjay Feb 17 '20 at 08:17
  • 1
    What's your JSON like? What's the exception? – cassiomolin Feb 17 '20 at 08:20
  • 1
    1. The point class is provided by com.vividsolutions.jts.geom.Point. 2. The exception when I return the Point object: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.vividsolutions.jts.geom.Point["envelope"]->com.vividsolutions.jts.geom.Point["envelope"]-> – Adnan Arif Sait Feb 17 '20 at 08:49

1 Answers1

2

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.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    Got it, Thanks. I assumed that the Geometry classes (Point, Polygon, etc.), were analogous to POJO classes, but now I understand the necessity to setup custom serialisers and deserialisers. – Adnan Arif Sait Feb 17 '20 at 10:22
  • Can anyone provide what this serializer/deserializer looks like? – Mon Jul 18 '23 at 03:32
  • @Mon, much easier is to implement new `POJO` layer to which you cam map `com.vividsolutions.jts.geom` classes and after that serialise/deserialise these new `POJO` classes. – Michał Ziober Jul 18 '23 at 08:27