1

I have Spring Rest Service Payload Object with Date inside it.

Now I would like to throw Parsing or Validation Exception if the Date passed is not in yyyy-MM-dd format. Example - if they 12-01-2016, I want to throw exception except for 2016-12-01. Please advise

Note - I am trying parse Date directly here using getDob and I have seen lot of examples which are parsing String.

public class PayLoad {
    private Date dob = null;
    @JsonFormat(pattern = "yyyy-MM-dd")
    public Date getDob() {
        return dob;
    }
    @JsonFormat(pattern = "yyyy-MM-dd")
    public void setDob(Date dob) {
        this.dob = dob;
    }
}
denvercoder9
  • 2,979
  • 3
  • 28
  • 41
Imran
  • 5,542
  • 3
  • 23
  • 46

1 Answers1

2

First, I wouldn't model a date of birth as a java.util.Date. You should use java.time.LocalDate.

Second, you probably need a custom JsonSerializer/JsonDeserializer here if you're using Jackson. That should be trivial to write. Here's an example.

Community
  • 1
  • 1
massfords
  • 689
  • 7
  • 12
  • Thank you very much for the advise. I noticed one thing that by default LocalDate seralizer is taking format yyyy-MM-dd which is good and what I was looking. Also I am wondering is there a way to catch this parse/validation exception with the following answer in the example you have given. http://stackoverflow.com/a/38731094/5030709 – Imran Dec 31 '16 at 04:33
  • Spring and similar frameworks support the Java Validation API. In some cases, I've opted to have dates modeled as Strings for the REST call and then map them internally from DTO to domain objects that have proper date/time objects. For your purposes, maybe you could just have your custom deserializer throw a special exception and then have an ExceptionMapper for that exception that returned a 400 or similar response. – massfords Dec 31 '16 at 23:22