Have jackson ignore fields that are lazy initialized when serialized in json

I use Spring and create a REST service.

Here is part of my controller:

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

Character roles are lazy initialized and not needed at that time. When (1) is commented out, everything will fail with

org.springframework.http.converter.HttpMessageNotWritableException: Failed to write JSON: failed to lazily initialize the collection role: no.something.project.Person.roles, failed to initialize the proxy - no session, etc.

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

. , - , , null.

: @JsonIgnore , , .

+5

All Articles