长值的spring启动验证

长值的spring启动验证,spring,spring-boot,validation,hibernate-validator,spring-validator,Spring,Spring Boot,Validation,Hibernate Validator,Spring Validator,这是我们将映射传入请求的类 @Getter @Setter public class FooRequest { @Size(max = 255, message = "{error.foo.name.size}") private String name; @Digits(integer = 15, fraction = 0, message = "{error.foo.fooId.size}") private Long

这是我们将映射传入请求的类

@Getter
@Setter
public class FooRequest {
    @Size(max = 255, message = "{error.foo.name.size}")
    private String name;

    @Digits(integer = 15, fraction = 0, message = "{error.foo.fooId.size}")
    private Long fooId;

    @Digits(integer = 15, fraction = 0, message = "{error.foo.barId.size}")
    private Long barId;
    }
我使用了
javax.validation.constraints.*
如上所述。如果我们发送请求,比如

{
    "name": "Test",
    "fooId": "0001234567",
    "barId": "0003456789"
    }
然后,它工作正常,我们可以将结果保存在数据库中,但如果我们像这样发送:

{
    "name": "Test",
    "fooId": 0001234567,
    "barId": 0003456789
    }
然后我们得到了
400个错误请求
。我不明白我做错了什么,我只是想确保用户发送长度在1-15之间的数字,并希望将其映射到
Long
变量。是因为分数还是因为所有这些值都以0开头?

第二个JSON不是a,因为前面的零

背景 Spring使用库进行JSON交互

如果您试图解析第二个JSON,默认情况下Jackson的
ObjectMapper
会抛出:

公共类主{
公共静态void main(字符串[]args)引发IOException{
ObjectMapper ObjectMapper=新的ObjectMapper();
objectMapper.readValue(“{\'name\':\'Test\',\'fooId\':0001234567,\'barId\':0003456789}”,FooRequest.class);
}
}
例外情况是:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Invalid numeric value: Leading zeroes not allowed
 at [Source: (String)"{"name": "Test", "fooId": 0001234567, "barId": 0003456789}"; line: 1, column: 28]
可以通过以下方式允许前导零:

公共类主{
公共静态void main(字符串[]args)引发IOException{
ObjectMapper ObjectMapper=新的ObjectMapper();
configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_zero,true);
FooRequest-FooRequest=objectMapper.readValue(“{\“name\”:\“Test\”,\“fooId\”:0001234567,\“barId\”:0003456789}”,FooRequest.class);
System.out.println(fooRequest.getBarId());
}
}
或者通过spring Boot的
应用程序在spring中运行。属性

spring.jackson.parser.allow-numeric-leading-zeros=true
然后,第二个JSON将被成功解析

为什么它与第一个JSON一起工作? 因为默认情况下Jackson's是打开的

从其javadoc:

启用此功能时,只要文本值匹配,就允许从JSON字符串进行转换(例如,允许字符串“true”等效于JSON布尔标记
true
;或字符串“1.0”等效于
double


因为所有这些值都是从0开始的


结果是,是的,但原因稍有不同

谢谢@denis-zavedeev。它使用了“spring.jackson.parser.allow numeric leading zeros=true”