Search code examples
spring-bootbean-validation

Spring Boot Bean Validation for LocatDateTime


I have Person POJO where in private LocalDateTime startTime; attribute as below,

    @NotNull
    @JsonProperty("startTime")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm:ssZ", iso = DateTimeFormat.ISO.DATE_TIME)
    private LocalDateTime startTime;

I need to send "startTime": "2020-08-20T12:30:18+0000", from my JSON input to a rest end point.

I get bad request, is there anything missing in my validation? I tried with removing Z and adding @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ssZ") also but not working.


Solution

  • You can write a Deserializer for LocalDateTime for your desired format and use on field.

    @NotNull
    @JsonDeserialize(using = JacksonLocalDateTimeDeserializer.class)
    private LocalDateTime startTime;
    

    Custom Deserializer implementations

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