针对LocatDateTime的Spring Boot Bean验证

问题描述

我有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;

我需要将JSON输入中的"startTime": "2020-08-20T12:30:18+0000",发送到其余端点。

我收到了错误的请求,我的验证中是否缺少任何内容?我尝试删除Z添加@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd@HH:mm:ssZ"),但没有用。

解决方法

您可以为所需的格式编写LocalDateTime的反序列化程序,并在字段中使用。

@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"));
  }
}