Spring LocalDateTime 的引导 Bean 验证
Spring Boot Bean Validation for LocatDateTime
我有 Person POJO,其中 private LocalDateTime startTime;
属性如下,
@NotNull
@JsonProperty("startTime")
@DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm:ssZ", iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime startTime;
我需要将 "startTime": "2020-08-20T12:30:18+0000",
从我的 JSON 输入发送到休息端点。
我收到了错误的请求,我的验证中是否缺少任何内容?我尝试删除 Z
并添加 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ssZ")
但没有用。
您可以为 LocalDateTime 编写一个 Deserializer,以获得所需的格式并在字段上使用。
@NotNull
@JsonDeserialize(using = JacksonLocalDateTimeDeserializer.class)
private LocalDateTime startTime;
自定义解串器实现
import java.time.format.DateTimeFormatter;
public class JacksonLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
private static final long serialVersionUID = 9152770723354619045L;
public JacksonLocalDateTimeDeserializer() { this(null);}
protected JacksonLocalDateTimeDeserializer(Class<LocalDateTime> type) { super(type);}
@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
if (parser.getValueAsString().isEmpty()) {
return null;
}
return LocalDateTime.parse(parser.getValueAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
}
}
我有 Person POJO,其中 private LocalDateTime startTime;
属性如下,
@NotNull
@JsonProperty("startTime")
@DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm:ssZ", iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime startTime;
我需要将 "startTime": "2020-08-20T12:30:18+0000",
从我的 JSON 输入发送到休息端点。
我收到了错误的请求,我的验证中是否缺少任何内容?我尝试删除 Z
并添加 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ssZ")
但没有用。
您可以为 LocalDateTime 编写一个 Deserializer,以获得所需的格式并在字段上使用。
@NotNull
@JsonDeserialize(using = JacksonLocalDateTimeDeserializer.class)
private LocalDateTime startTime;
自定义解串器实现
import java.time.format.DateTimeFormatter;
public class JacksonLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
private static final long serialVersionUID = 9152770723354619045L;
public JacksonLocalDateTimeDeserializer() { this(null);}
protected JacksonLocalDateTimeDeserializer(Class<LocalDateTime> type) { super(type);}
@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
if (parser.getValueAsString().isEmpty()) {
return null;
}
return LocalDateTime.parse(parser.getValueAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
}
}