How to intercept the marshmalling (json serial/deserial) from a CrudRepository declared as a @RepositoryRestResource?

StackOverflow https://stackoverflow.com/questions/21919723

Question

Given this repository

@RepositoryRestResource( path = "u", itemResourceRel="ui", collectionResourceRel = "us")
public interface IUserRepository extends CrudRepository<Users, Long> {
}

When I go through a controller to call my service method findAllUsers(). I transform the list of entities result (returned by userRepository.findAll() method provided for free) to a list of domain model objects. This list of domain model objects will get properly deserialize into JSON because I am controlling how to do the deserialization. There is a specific reason why I am doing this, see further below.

Now, if I want to use the userRepository directly, I am running into a loop during the serialization because the object being deserialized are coming from the library com.vividsolutions.jts.geom.Geometry. This class contains a method as described below

  Geometry getEnvelope() Returns this Geometrys bounding box.

During the deserialization, jackson runs into a loop, because of it. I am able to correct the deserialization process within my controller. How could I intercept the deserialization from a CrudRepository?

The first idea that came to me was to create an implementation of my interface and override all methods, but it defeats the purpose of doing boiler-plate code.

Was it helpful?

Solution

You show the usage of @RepositoryRestResource I am assuming you're using Spring Data REST to export your repositories. For standard Spring MVC marshaling configuration see the reference docs.

Precisely speaking, you're not intercepting the repositories. Spring Data REST uses Jackson to marshal and unmarshal the responses and requests. Hence you simply customize the Jackson ObjectMapper that SD REST will use. To do so, you extend RepositoryRestMvcConfiguration and override configureJacksonObjectMapper(…):

class MyConfiguration extends RepositoryRestMvcConfiguration {

  protected void configureJacksonObjectMapper(ObjectMapper mapper) {
    // register custom serialializers, modules etc.
  }
}

For customization options in general, have a look at the Jackson reference documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top