提问者:小点点

如何使用Spring自定义Jackson ObjectMapperapplication.properties?


我想启用以下jackson mapper功能:MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES

根据https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html:

可以在application.properties中配置如下:Spring. jackson.mapper.accept_case_insensitive_properties=true

但是:

@RestController
public class MyServlet {
    @RequestMapping("/test")
    public void test(@Valid TestReq req) {

    }
}

public class TestReq {
    @NotBlank
    private String name;
}

用法:

localhost:8080/test?name=test //works
localhost:8080/test?Name=test //fails with 'name may not be blank'

因此,没有考虑大小写不敏感的性质。但是为什么呢?

顺便说一句:即使使用Jackson2ObjectMapperBuilderCustomizer显式也不起作用:

@Bean
public Jackson2ObjectMapperBuilderCustomizer initJackson() {
    Jackson2ObjectMapperBuilderCustomizer c = new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.featuresToEnable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
        }
    };

    return c;
}

spring-boot-1.5.3。释放


共2个答案

匿名用户

根据Spring文档,您可以自定义它。

我通过像这样设置我的application. yml来解决这个问题(Spring 2.0):

 spring:
  jackson:
    mapper:
      ACCEPT_CASE_INSENSITIVE_PROPERTIES: true

您是否尝试将设置accept_case_insensitive_properties更改为大小写?

您还可以通过如下设置将输出保持为大写:

  jackson:
    mapper:
      ACCEPT_CASE_INSENSITIVE_PROPERTIES: true
    property-naming-strategy: com.fasterxml.jackson.databind.PropertyNamingStrategy.PascalCaseStrategy

请注意,PascalCaseStrategy现在已弃用,但仍在工作。

匿名用户

答案很简单:不可能。

Jackson2ObjectMapperBuilderCustomizer只影响POST请求JSON,对获取查询绑定没有影响。