RequestBody JSON格式具有单引号

use*_*589 2 java spring jackson

我的SpringBoot应用程序中有一个控制器类。

@RestController
@RequestMapping("/{database}/alerts")
public class ControllerB {
  @Autowired private ServiceB serviceB;

  @Autowired
  private B b;

  @Autowired
  ControllerB(B b,ServiceB serviceB){
      this.b = b;
      this.serviceB = serviceB;
  }

  @RequestMapping(method = RequestMethod.POST)
  public B dosomethingCrazy(@RequestBody BImpl bimpl)  {


      String response = serviceB.dosomethingImportant();
      return bimpl;

  }

}
Run Code Online (Sandbox Code Playgroud)

当requestBody的值中包含单引号时,就会出现问题。例如,如果请求正文为{“ name”:“ peter o'toole”},则会抛出http 400

“状态”:400,“错误”:“错误的请求”,“异常”:“ org.springframework.http.converter.HttpMessageNotReadableException”,“消息”:“ JSON解析错误:VALUE_STRING中意外的输入结束

知道杰克逊如何将单引号值映射到对象字段吗?

Dhe*_*rik 5

创建此类以设置 Jackson 并启用单引号:

@Configuration
public class JsonConfigurer {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
        return objectMapper;
    }

}
Run Code Online (Sandbox Code Playgroud)


Wim*_*uwe 5

application.properties文件中设置以下属性:

spring.jackson.parser.allow-single-quotes=true
Run Code Online (Sandbox Code Playgroud)