Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have jackson ignore fields that are lazy initialized when serializing to json

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.

like image 253
Matsemann Avatar asked Mar 13 '13 19:03

Matsemann


People also ask

How do you ignore certain fields based on a serializing object to JSON?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How do I ignore null values in JSON response Jackson?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

How do you tell Jackson to ignore a field during deserialization?

Overview So when Jackson is reading from JSON string, it will read the property and put into the target object. But when Jackson attempts to serialize the object, it will ignore the property. For this purpose, we'll use @JsonIgnore and @JsonIgnoreProperties.

How do I ignore values in JSON response?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.


1 Answers

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

like image 179
Michail Nikolaev Avatar answered Sep 29 '22 12:09

Michail Nikolaev