I have recently upgraded my Spring version to 3.2.0 from 3.1.2. I find that that JSON properties like wrap root element, prevent null values that are defined in ObjectMapper
Disclaimer: I could not determine why the code in question is not working, but I could reproduce the problem. This answer does provide an alternate approach that works for me.
It could be a bug, as I can reproduce the problem with both with explicit config:
and via the mvc:message-converter:
where both give me {"foo":null,"bar":"bar"} when using the example class
Demo.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.codehaus.jackson.annotate.JsonProperty;
@Controller
@RequestMapping("/data")
public class Data {
@RequestMapping
@ResponseBody
public Dummy dataIndex() {
return new Dummy();
}
public class Dummy {
String foo = null;
@JsonProperty
public String foo() {
return foo;
}
String bar = "bar";
@JsonProperty
public String bar() {
return bar;
}
}
}
However, I would have thought the mvc:message-converter method would work, only because I have seen issues overriding the default bean registration that performs (see Web MVC Framework) and using the nested configuration is preferred(?).
Maybe the Jackson 2 support has caused some backwards compatibility issues with Jackson 1?
However, switching to the MappingJackson2HttpMessageConverter (supported in Spring 3.1.2 and Spring 3.2), I am able to alter the ObjectMapper configuration to not write null values and wrap the JSON output... but only when using the config inside the !
I get {"Dummy":{"bar":"bar"}} with the following changes:
pom.xml
com.fasterxml.jackson.core
jackson-core
2.1.0
com.fasterxml.jackson.core
jackson-databind
2.1.0
com.fasterxml.jackson.core
jackson-annotations
2.1.0
CustomJacksonObjectMapper.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import static com.fasterxml.jackson.annotation.JsonInclude.*;
public class CustomJacksonObjectMapper extends ObjectMapper {
public CustomJacksonObjectMapper() {
super();
this.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
this.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
this.setSerializationInclusion(Include.NON_NULL);
}
}
Demo.java switch to new package structure for Jackson 2
import com.fasterxml.jackson.annotation.JsonProperty;
demo-servlet.xml
Lastly, according to the SerializationConfig.Feature documentation, WRITE_NULL_PROPERTIES feature is deprecated < v2.0 and you should be using SerializationConfig.setSerializationInclusion() anyway. I assume this is why the @SuppressWarnings("deprecation") exists in your code. In Jackson >= v2.0, it has been removed, hence the code change in the CustomJacksonObjectMapper.java example.
Configuring ObjectMapper in Spring proposes an alternate solution.
Hope it helps!