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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With