首页 > 解决方案 > Json 整数被读取为 java Boolean true

问题描述

在 REST API 请求 json 正文中,我正在传递"argument1":true它并且它可以工作。但我发现,当使用任何数字时,它都会将其转换为真。只有在显式使用时false它才会变为假。我正在使用 Spring BootResponseEntityExceptionHandler@RestControllerAdvice处理所有异常。534转换为时如何抛出任何异常true

标签: jsonspring-bootboolean

解决方案


在您的控制器中添加一个带有注释的方法@InitBinder并提供一个自定义布尔编辑器

@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
    webDataBinder.registerCustomEditor(Boolean.class, new CustomBooleanEditor("true", "false", false));
}

Spring 注册一个默认的CustomBooleanEditor映射“true”、“on”、“yes”和任何非零数字作为true(也允许空值作为)在值无效时false抛出。IllegalArgumentException

您可以覆盖它或提供自己的实现来引发特定异常。


推荐阅读