7

I use Spring and am creating a REST service.

Here's a part of my controller:

@RequestMapping("/get")
public @ResponseBody Person getPerson() {
    Person person = personRepository.findOne(1L);
    //(1) person.setRoles(null);
    return person;
}

The person's roles are lazy initialized, and not needed at the time. When (1) is commented out, everything will fail with an

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: no.something.project.Person.roles, could not initialize proxy - no Session etc.

I can solve this by doing as (1), manually set it to null (or some other value), so it will not fail when Jackson tries to serialize my object.

However, this is annoying and must be done many times different places. I'd like for some easy solution to just ignore those lazy initialized fields when not initialized, or just set them to null.

Note: @JsonIgnore on the values on the object is not a solution, as in other cases I want those values to be included.

DataNucleus
  • 15,497
  • 3
  • 32
  • 37
Matsemann
  • 21,083
  • 19
  • 56
  • 89

1 Answers1

5

Check Jackson Views for Jackson Filters (both are supported by Spring as I remember).

Also, to work with lazy fields (if they are not excluded) you need - jackson-module-hibernate

Michail Nikolaev
  • 3,733
  • 22
  • 18
  • How do I use jackson-module-hibernate with Spring? The code on the wiki misses something. – Matsemann Apr 04 '13 at 21:31
  • @Matsemann I got the solution here and provided the working code: http://stackoverflow.com/questions/21708339/avoid-jackson-serialization-on-non-fetched-lazy-objects/21760361#21760361 – r1ckr Feb 14 '14 at 08:31