问题描述
我正试图在Jackson的spring-boot应用程序中从JSON获取一个日期字段。 JSONFormat如下所示:
I am trying to get a date field from JSON in a spring-boot application with Jackson. The JSONFormat looks like this:
@NotNull(message = ValidationErrors.NOT_BLANK_MESSAGE)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd")
private Date date;
大多数情况都适用但是当我通过2017-0526时,它会自动转换它到2018年5月10日。
It works fine for most of the cases but when I pass 2017-0526, it is automatically converting it to 10th of May, 2018.
如果日期不是yyyyMMdd格式或包含减号,我想抛出异常。我尝试通过堆栈溢出和Jackson文档,但找不到任何东西。
I want to throw exception in case the date is not in the yyyyMMdd format or contains minus sign. I tried going through stack overflow and Jackson documentation, but couldn't find anything.
为什么JsonFormat接受否定日期?
Why is JsonFormat accepting negative dates?
是否有任何解决方法,以便在传递此类日期时抛出异常?
Is there any workaround for this, so that it throws exception when such dates are passed?
推荐答案
这是一个解析日期的底层Java类的问题。解析器默认为 lenient ,并将解析看似错误的日期。要进行更严格的解析,您需要使用方法。例如。解析带有日期字符串2017-0526的JSON时,此设置将导致 InvalidFormatException
:
This is an issue with the underlying Java class that parses dates. The parser is by default lenient and will parse dates that seem wrong. For stricter parsing you need to set the lenient property to false with the setLenient method. E.g. this setup will result in a InvalidFormatException
when parsing a JSON with a date string "2017-0526":
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
mapper.setDateFormat(df);
目前你无法通过 @JsonFormat
注释。版本2.9.0似乎有一个计划。
At the moment you can't configure this through a @JsonFormat
annotation. There seems to be a plan for that for version 2.9.0. Link to issue at github
这篇关于杰克逊接受负面日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!