How to configure jackson property naming strategy?

瘦欲@ 提交于 2019-12-11 01:30:22

问题


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

    ...
}


来源:https://stackoverflow.com/questions/36970807/how-to-configure-jackson-property-naming-strategy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!