如何配置jackson属性命名策略?

时间:2016-05-01 19:12:40

标签: java spring spring-mvc jackson spring-rest

此代码不起作用:

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

    ...
}

如何使用JavaConfig配置Jackson属性命名策略?

2 个答案:

答案 0 :(得分:2)

您可以使用以下方法来命名策略:

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());

答案 1 :(得分:-3)

解决方案:

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

    ...
}