本文介绍了SpringBoot使用@RequestBody注释原子地将整数转换为布尔值?如何拒绝将整数转换为布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的请求是这样的 application/json 类型: {"able":true} ,但是当我发送这样的请求 {"able:12345} ,字段 able 仍可以获取正确的值 true .为什么?

My request was an application/json type like this: {"able": true}, but when I send the request like this {"able":12345}, the field able still can get a correct value true. Why?

@PatchMapping("/{id}/path/{name}")
public ResponseEntity someMethod(
    @Valid @RequestBody SomeRequest request) {
    // do something
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class SomeRequest {
    @AssertTrue
    @NotNull
    private Boolean able;
}

推荐答案

因为当字段类型为bool时,jackson.databind会将int解析为bool.在 NumberDeserializers.BooleanDeserializer

Because jackson.databind will parse int to bool when field type is bool.Find code in NumberDeserializers.BooleanDeserializer

            JsonToken t = p.getCurrentToken();
            if (t == JsonToken.VALUE_TRUE) {
                return Boolean.TRUE;
            }
            if (t == JsonToken.VALUE_FALSE) {
                return Boolean.FALSE;
            }
            return _parseBoolean(p, ctxt);

_parseBoolean(p,ctxt)会将int解析为bool.

_parseBoolean(p, ctxt) will parse int to bool.

我们可以不使用默认值来自己做.

We can do it by ourselves not use default.

  1. 创建我们的bool deser类.
public class MyDeser extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonToken t = p.getCurrentToken();
        if (t == JsonToken.VALUE_TRUE) {
            return Boolean.TRUE;
        }
        if (t == JsonToken.VALUE_FALSE) {
            return Boolean.FALSE;
        }
        return null;
        // not parse int to bool but null and it may work ok.
        // if throw new IOException(), it will work fail. Maybe return null means use other deser to deal it. throw Exception means fail. I don't know it clearly.
    }
}
  1. 创建配置并注入SimpleModule bean.我在应用程序中写
 @SpringBootApplication
 @Configuration
 public class DemoApplication {
     @Bean
     public SimpleModule addDeser() {
         return new SimpleModule().addDeserializer(Boolean.class, new MyDeser());
     }
     public static void main(String[] args) {
         SpringApplication.run(DemoApplication.class, args);
     }
 }

这篇关于SpringBoot使用@RequestBody注释原子地将整数转换为布尔值?如何拒绝将整数转换为布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:33