Altus34 Altus34 - 1 year ago 288
JSON Question

Spring boot Jersey Jackson

I have a question related to the Jackson configuration on my Spring boot project

As described on spring boot blog

I try to customize my Object serialization.

After added a new config bean in my config

public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

return builder;

When I try to output an instance of my class User the json result is not in CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES

Class User {
private String firstName = "Joe Blow";

public String getFirstName() {
return firstName;

json output is :

"firstName": "Joe Blow"

and not

"first_name": "Joe Blow"

Maybe I need to register something in my Jersey config to activate my custom obejctMapper Config

public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {


Answer Source

The general way to configure the ObjectMapper for JAX-RS/Jersey applications is use a ContextResolver. For example

public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper mapper;

    public ObjectMapperContextResolver() {
        mapper = new ObjectMapper();

    public ObjectMapper getContext(Class<?> type) {
        return mapper;

It should be picked up with the package scan, or you can explicitly register it, if it's not within the package scope

public JerseyConfig() {
    register(new ObjectMapperContextResolver());
    // Or if there's is an injection required
    // register it as a .class instead of instance

The ContextResolver is called during the marshalling and unmarshalling. The class/type being serialzed or deserialized into will be passed to the getContext method. So you could even use more than one mapper for different types, or even more use cases. For instance, you could inject other Jersey contexts (with @Context), say UriInfo, to decide base on a URI, which mapper should be used. See more about @Context injections, here


Starting from Spring Boot 1.4, you can just create an ObjectMapper Spring bean, and Spring Boot will create the ContextResolver for you, and use your ObjectMapper

// in your `@Configuration` file.
public ObjectMapper mapper() {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download