Validate Date in the request body - java

I have a request body have date field and I want to validate the input of the date and return error code 400 BadRequest if the format is wrong.
If I use the JsonFormat then it throws error 500:
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date dateAt;
So I changed the field to String and then parse and throw BadRequest format everywhere using the getDate()
I am not really satisfied with this approach. Is there any other elegant way to achieve this validation?
I think I will accept error 500 from JSON formatter and skip my custom exception.

Since Java 8, you should avoid using Date. Java 8 brought an entirely new date and time API.
According to your question, a suitable replacement for Date would be LocalDate, which is expected to be in the format yyyy-MM-dd.
Jackson has a module supporting the new date and time API and an exception will be thrown if the date is not in the correct format. When serializing, you want to make sure the WRITE_DATES_AS_TIMESTAMPS feature is disabled, so the values will be written according to the ISO 8601 format.

Related

deserializing error with date - JSON decoding error

I am getting a response from an api and it is failing to deserialize a date which looks like this "2021-09-10T21:48:35.352+0000". I have set up attribute in my class like below
#JsonProperty("processedAt")
private LocalDateTime processedAt;
org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize value of type java.time.LocalDateTime from String "2021-09-10T21:48:35.352+0000": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2021-09-10T21:48:35.352+0000' could not be parsed, unparsed text found at index 23;
what format of date should I be using in class to get the date out and not fail on deserializing. thanks in advance
By default Jackson does not support this date time format pattern. Therefore you need to explicitly mention that using #JsonFormat annotation. Like this,
#JsonProperty("processedAt")
#JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private LocalDateTime processedAt;
Looking at your datetime format, you should probably use OffsetDateTime instead of LocalDateTime. Otherwise your timezone will be ignored (If you local timezone is +0000, then LocalDateTime should be fine).
#JsonProperty("processedAt")
#JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private OffsetDateTime processedAt;
Update
If you use OffsetDateTime, then you don't need to explicitly mention the pattern using #JsonFormat annotation. Something like this sufficient.
#JsonProperty("processedAt")
private OffsetDateTime processedAt;
I did not check but you are using LocalDateTime and are trying to deserialize a ZonedDateTime. Maybe change the type?
That is also in agreement with the error message that states that the error is at position 23. Exactly where the unexpected zone information starts.

Serialize Date: Swagger and Spring-MVC

I'm using swagger-ui and a stub server in Java Spring-MVC generated using swagger-codegen. I have a date format somewhere and if I enter some date, it always returns me the UNIX Date Time format. I would like to have the RFC-3339 format for the date and date-time. Does anyone knows how to do this?
I found the answer..
I had to overwrite the JsonFormat since I'm returning a JSON object..
Therefore, if you have the same problem as me, use:
#JsonFormat(pattern="...")
Date foo;
Do not forget to use import com.fasterxml.jackson.annotation.JsonFormat;

Java parse a date in the format YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HHMM|-HHMM|Z]

How can i parse a date that can come in the specified formart.
YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HHMM|-HHMM|Z]
I could use the following code for a specific dateformart:
new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss.S").parse(date_collected);
But my problem is dealing with the other possibilities

Timestamp getting as long instead of date format

I have a one rest method from Spring3 which returns expected JSON response except date which is in timestamp.
In database date is stored as 2013-08-08 00:30:00. Before sending response to the application, the date I am getting as 2013-08-08 00:30:00. I have checked it in debug mode. But after complete execution of rest-service, I got the date in long format as 1375902000000.
I want to return same timestamp format instead of long format.
I don't want to convert long timestamp to again date format at client side.
By default it is serialized as long if you want to send it like 2013-08-08 00:30:00 you may try asString()
You could do the following to keep your desire date format:
Declare the bean property as String.
Format the date object according to your desire format, example yyyy-dd-MM hh:mm:ss

JSON parse date and time?

Im having a little issue with parsing json date.
Here is what I would like to parse:
{"driver": "247","firstName": "XXXXX","lastName": "XXXXX","lastLatitudeUpdate": "5/21/2012 4:49:17 PM","suspended": "false","checkedin": "0"}
I am having trouble parsing "lastLatitudeUpdate" is it because there are spaces in between? Thanks in advance for the help.
Assuming you are on Android and therefore working with java (yes you don't mention that, only the tag in your question suggests it...)
Like mentioned here (and in various other places) you can parse a date in java using the SimpleDateFormat class:
SimpleDateFormat parserSDF=new SimpleDateFormat("M/d/yyyy h:m:s a");
Date d = parserSDF.parse(dateField,0);
Of course you have to first parse you json input with some library (e.g. standard library from json.org or Google gson) and then parse the string you'll get there for the field into a date.
Short answer: No, there is no way for the JSON engine to recognize a string as a Date object.
Long answer:
There is no 'date' type in JSON. However, this JSON is fine, the catch is that lastLatitudeUpdate will be parsed as a string. In order to convert this to a date you should try something like
var my_object= JSON.parse({"driver": "247","firstName": "XXXXX","lastName": "XXXXX","lastLatitudeUpdate": "5/21/2012 4:49:17 PM","suspended": "false","checkedin": "0"});
my_object.lastLatitudeUpdate= Date.parse(my_object.lastLatitudeUpdate)
This function will give a timestamp. However, you have to make sure the string is correctly recognized, you may have to do some extra work.
Some links for hints
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
http://www.java-samples.com/showtutorial.php?tutorialid=406
How are you parsing the date? In Chrome this seems to work fine:
new Date("5/21/2012 4:49:17 PM");
Mon May 21 2012 16:49:17 GMT-0400 (US Eastern Daylight Time)

Categories