How to configure jackson property naming strategy?

2019-07-27 06:14发布

问题:

This code does not work:

@Configuration
public class RepositoryRestMvcConfig extends RepositoryRestMvcConfiguration {
    ...

    @Bean
    @Override
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = super.objectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        return mapper;
    }

    ...
}

How to configure Jackson property naming strategy with JavaConfig?

回答1:

You can use below approach for naming strategy :

class MyBean {
     private String inReply;
     public void setInReplyToUserId(String s) { 
       inReply = s; 
     }
     public String getInReplyToUserId() { 
       return inReply; 
     }
  }

  class MyNaming extends PropertyNamingStrategy {
    @Override
    public String nameForGetterMethod(MapperConfig<?> config,
         AnnotatedMethod method, String defaultName)
    {
      // Replace underscore+letter with upper-case(letter)
      // (left as exercise to reader!)
      return convertName(defaultName);
    }
  }

  objectMapper.setPropertyNamingStrategy(new MyNaming());


回答2:

Solution:

@Configuration
public class RepositoryRestMvcConfig extends RepositoryRestMvcConfiguration {
    ...

    @Bean
    @Override
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = super.objectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        return mapper;
    }

    @Bean
    @Override
    public ObjectMapper halObjectMapper() {
        ObjectMapper mapper = super.halObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        return mapper;
    }

    ...
}