In a Spring Boot app, I read data from JSON file and for the date fields, I get the following error:
2022-08-08 23:39:25 - Resolved [com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type
java.time.LocalDate
from String "5/8/1985": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '5/8/1985' could not be parsed at index 0 at [Source: (File); line: 1, column: 113] (through reference chain: java.util.ArrayList[0]->...
The date format in the JSOn file is like "3/18/1965"
Here is my entity and request below:
public class Employee {
// code omitted
// I have really no idea how to format this date
@JsonFormat(pattern = "dd.mm.yyyy", shape = JsonFormat.Shape.STRING)
private LocalDate birthDate;
}
The problem is related to format, but I have tried many combinations and I need to be clarified about the following issues to fix the problem:
1. Which data type should I use to keep date (no need time and time zone)?
2. How can I format date field read from JSON? Which annotation should I use and should I also use this annotation in Request and DTO classes where birthDate
field is defined?
CodePudding user response:
Your formatting pattern fails on multiple points:
- You specify FULL STOP (dot) character as the delimiter in your formatting pattern,
dd.mm.yyyy
. But your example input data"5/8/1985"
has SOLIDUS (slash) character. - You used a
m
which means “minutes” where you need to useM
for month. See Comment by Kareem.
You need to study the DateTimeFormatter
class Javadoc more carefully. And practice the parsing before use with Jackson.
You asked:
Which data type should I use to keep date (no need time and time zone)?
Use java.time.LocalDate
.
Avoid the terrible java.sql.Date
class that pretends to represent a date. It was supplanted by LocalDate
years ago, with the adoption of JSR 310.