英文:
Spring boot with Jackson Unable to Validate java.util.Date
问题
我需要使用模式 'yyyy-MM-dd HH:mm:ss' 验证日期。我正在使用带有 Jackson 版本 2.10.2 的 util 日期,由于公司要求,我无法迁移到 Java 8 LocalDate。我发现许多关于这个问题的问答,但没有一个能够很好地解决我的问题。
import com.fasterxml.jackson.annotation.*;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"provisionedDate",
})
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE)
public class PostProvisionCallback implements Serializable {
@JsonProperty("id")
private String id;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@NotNull(message = "provisionedDate 不能为空")
@JsonProperty("provisionedDate")
private Date provisionedDate;
}
即使我输入无效日期 '20201-0612213-17 09:26:12',仍然会被评估为有效日期。有什么完美的解决方案吗?但是,如果我将日期输入为 '2020/03/04 09:26:12',则应用程序会抛出内部服务器错误异常。
英文:
I need to validate date with pattern 'yyyy-MM-dd HH:mm:ss'. I'm using util date with jackson version 2.10.2
and I can't move to java 8 localdate as company requirement. I found many Q&A regarding this issue and none of them solve my problem properly.
import com.fasterxml.jackson.annotation.*;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"provisionedDate",
})
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE)
public class PostProvisionCallback implements Serializable {
@JsonProperty("id")
private String id;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@NotNull(message = "provisionedDate cannot be null")
@JsonProperty("provisionedDate")
private Date provisionedDate;
}
even I enter invalid date like '20201-0612213-17 09:26:12',still this is evaluate as valid date. What is the perfect solution for this.? but if I enter date as '2020/03/04 09:26:12' then application throw internal server error exception.
答案1
得分: 3
这是SimpleDateFormat
负责实际可配置解析的部分。您可以将lenient
的值设置为false
。
将
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
替换为
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
英文:
It is the SimpleDateFormat
that handles the actual configurable parsing. You can set the value of lenient
as false
.
Replace
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
with
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论