In my application I need to support both json and xml response format and want to omit null values from responses. In the json response this works fine, but not in xml response. The result:
{
"anotherValue": "value"
}
and:
<MyDoc>
<value/>
<anotherValue>value</anotherValue>
</MyDoc>
I would like the xml to look like:
<MyDoc>
<anotherValue>value</anotherValue>
</MyDoc>
Annotating every response class with @JsonInclude(JsonInclude.Include.NON_NULL)
is a possible solution but I want it configured globally. My code:
@SpringBootApplication
@RestController
@Configuration
public class Application {
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
return builder
.serializationInclusion(JsonInclude.Include.NON_NULL)
.serializationInclusion(JsonInclude.Include.NON_EMPTY)
.build();
}
@GetMapping(value = "api/json", produces = APPLICATION_JSON_VALUE)
public MyDoc json() {
return new MyDoc(null, "value");
}
@GetMapping(value = "api/xml", produces = APPLICATION_XML_VALUE)
public MyDoc xml() {
return new MyDoc(null, "value");
}
public static class MyDoc {
public String value;
public String anotherValue;
public MyDoc(String val1, String val2) {
this.value = val1;
this.anotherValue = val2;
}
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
What am i missing here? Any help is appreciated! Thanks, DagR
this works fine for me...
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
};
}
note for outputting XML you need to use jackson-dataformat-xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>