I'm creating a rest
service with spring
and want to offer a json
response:
@RequestMapping(value = "/test",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MyResponse content() {
return rsp;
}
MyResponse
may contain null
values which should not be returned in the JSON
response (these params should just be removed).
@XmlRootElement
class MyResponse {
}
Is that possible?
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.
Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!!
You should definitely include it if there is any need to distinguish between null and undefined since those have two different meanings in Javascript. You can think of null as meaning the property is unknown or meaningless, and undefined as meaning the property doesn't exist.
Try this :
@JsonInclude(JsonInclude.Include.NON_NULL)
class MyResponse {
...
}
You'll need to update your dependencies and import this :
import com.fasterxml.jackson.annotation.JsonInclude;
Globally remove null
property.
spring.jackson.default-property-inclusion = non_null
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