How to configure jackson property naming strategy?

2019-07-27 05:57发布

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?

2条回答
Summer. ? 凉城
2楼-- · 2019-07-27 06:16

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());
查看更多
闹够了就滚
3楼-- · 2019-07-27 06:26

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;
    }

    ...
}
查看更多
登录 后发表回答