Spring Rest Service: How to Configure to Remove Null Objects in JSON Response

How to remove null parameters in a json rest response?

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;

How to remove null attributes while constructing the JSON response

You might add simply @JsonInclude annotation then include non null values.

@JsonInclude(JsonInclude.Include.NON_NULL)
@ManyToOne
@JoinColumn(name="author_id")
private Author author;

How to not return null value in ResponseEntity?

I think this simple solution could help you

https://stackoverflow.com/a/36515285/5108695

Since Jackson is being used, you have to configure that as a Jackson property. In the case of Spring Boot REST services, you have to configure it in application.properties or application.yml:

spring.jackson.default-property-inclusion = NON_NULL

how to configure spring mvc 3 to not return null object in json response?

Yes, you can do this for individual classes by annotating them with @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) or you can do it across the board by configuring your ObjectMapper, setting the serialization inclusion to JsonSerialize.Inclusion.NON_NULL.

Here is some info from the Jackson FAQ: http://wiki.fasterxml.com/JacksonAnnotationSerializeNulls.

Annotating the classes is straightforward, but configuring the ObjectMapper serialization config slightly trickier. There is some specific info on doing the latter here.

How to ignore null or empty properties in json, globally, using Spring configuration

If you are using Spring Boot, this is as easy as:

spring.jackson.serialization-inclusion=non_null

If not, then you can configure the ObjectMapper in the MappingJackson2HttpMessageConverter like so:

@Configuration
class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for(HttpMessageConverter converter: converters) {
if(converter instanceof MappingJackson2HttpMessageConverter) {
ObjectMapper mapper = ((MappingJackson2HttpMessageConverter)converter).getObjectMapper()
mapper.setSerializationInclusion(Include.NON_NULL);
}
}
}
}


Related Topics



Leave a reply



Submit