Formatting date retrieved from JSON file in Java - java

I import a JSON file and try to format date properly. But every time I try a different combination as mentioned on this or some similar threads, I always get "Cannot deserialize value of type java.time.LocalDate from String "09.09.1977": Failed to deserialize java.time.LocalDate" error.
Before fixing the problem, I think I need to be clarified about the following questions (I need to format Date in "dd.MM.yyy" format):
1) Does the date field have in the JSON file to be a specific format?
2) I have entity and dto classes where my date field is located. Should I apply related format annotations, etc. in these classes on the date field as shown below?
Here are some examples I tried:
#DateTimeFormat(pattern = "dd.MM.yyyy", iso = DateTimeFormat.ISO.DATE_TIME)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
#JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDate startDate;
Or how can I format the read json file in "dd.MM.yyyy"? Here is the related code block where I retrieve the file and convert from EmployeeRequest request to Employee:
final List<Employee> employees = requests.stream()
.map(EmployeeRequestMapper::mapToEntity)
.toList();

[tl;dr] Use the same data type on class level and in annotations
You currently try to use an automatic de-/serialization of a String that represents a date (only year, month of year and day of month). For this to work automatically, you need to annotate the class member with the classes that are responsible for serialization and deserialization. The one you are currently using is a LocalDateTimeSerializer, though it should be a LocalDateSerializer, because the current one will expect a time-of-day part in the String to be (de-)serialized, which it hasn't and your target class is a private LocalDate startDate.
In my opinion (not tested), your code should look like this:
#DateTimeFormat(pattern = "dd.MM.yyyy", iso = DateTimeFormat.ISO.DATE)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
private LocalDate startDate;

Related

#DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") is Not Working

#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
#Column(name = "modify_date")
private Date modifyDate;
When a new record is saved in the database it saves DateTime like this "2020-12-13 11:41:34.528000000" but I want it to save like this "2020-12-13 11:41:34"
There are several problems here. First, in your DB if you defined your column as date or timestamp you do NOT have any control of how the DB internally stores it. You may have control of how it would be represented by a client that reads it from DB. But that is all you need.
Second, Avoid outdated class Date and use java.time package. In your case, you might be interested in LocalDateTime or maybe ZonedDateTime class.
Once you change to appropriate class change the annotation
#DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
to
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
For more details see the answer to this question

LocalDateTime parses invalid dates to valid date and does not throw any exception

I am using LocalDateTime in the request body of my API in Spring.
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-mm-dd HH:mm:ss")
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
#JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime createdAt;
When I put an invalid date in request such as "2020-02-31 00:00:00" it is automatically converted to "2020-02-29 00:00:00". I want to throw Exception in case of an invalid date. It is mentioned in the official documentation that it converts to previous valid date .
In some cases, changing the specified field can cause the resulting date-time to become invalid,
such as changing the month from 31st January to February would make the day-of-month invalid.
In cases like this, the field is responsible for resolving the date.
Typically it will choose the previous valid date,
which would be the last valid day of February in this example.
You need to write a custom serializer for that.
class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("yyyy-mm-dd HH:mm:ss");
...
#Override
public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider)
throws IOException, JsonProcessingException {
// Do your validation using FORMATTER.
// Serialize the value using generator and provider.
}
}
Then you can just use it in your annotation.
#JsonSerialize(using = CustomLocalDateTimeSerializer.class)
Note that DateTimeFormatter throws an exception when formatting/parsing invalid values.
Check out the source of LocalDateTimeSerializer to know what has to be done. Check out Jackson Date - 10. Serialize Java 8 Date Without Any Extra Dependency for examples of writing a custom serializer. This is done analogous for a custom deserializer.

SpringBoot2 #DateTimeFormat annotation with LocalDateTime doesn't work as i expected

i want to convert LocalDateTime to YYYY-MM-DD HH:mm:ss format with #DateTimeFormat.
following is my source code.
Entity Class
#Entity // JPA Annotation
#Setter // Lombok Annotations
#Getter
public class CustomModel {
#DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime addDate;
#DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime lastModifyDate;
}
Controller Class
...
CustomModel customModel = new CustomModel();
customModel.setAddDate(LocalDateTime.now());
customModel.setLastModifyDate(LocalDateTime.now());
...
and following is result.
In above image, i expected '2019-08-11 03:08:56'.
But result format is '2019-08-11 03:08:56.814944'.
what is wrong??
You didn't put the thymeleaf template, but the #DateTimeFormat annotation will only be taken into account if you use double bracket rather than simple bracket, i.e. ${{model.addDate}} rather than ${model.addDate}.
You can use DateTimeFormatter class. But to convert, you need String representation of your date. Then parse it.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
customModel.setAddDate(LocalDateTime.parse(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)), formatter);
customModel.setLastModifyDate(LocalDateTime.parse(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)), formatter);

Jackson - Can't deserialize datetime with timezone offset 'unparsed text found at index 23'

My datetime has to come from frontend with timezone offset: 2017-07-04T06:00:00.000+01:00
I cannot deserialize it with Jackson.
The error is:
Text '2017-07-04T06:00:00.000+01:00' could not be parsed, unparsed
text found at index 23;
I was trying to Google the solution by all are about DateTime with Z at the end.
#NotNull
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS aZ")
private LocalDateTime time;
Is there any solution for that?
The pattern a is used to parse AM/PM, which is not in the input String, that's why you get a parse error.
The input format matches an OffsetDateTime, which can be parsed with the respective built-in formatter DateTimeFormatter.ISO_OFFSET_DATE_TIME, so you can use this formatter in a deserializer object and register it in the module. You must also remove the JsonFormat annotation from the field.
ObjectMapper om = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
module.addDeserializer(LocalDateTime.class, deserializer);
om.registerModule(module);
This will parse the input and convert it to a LocalDateTime. In the test I've made, the value of LocalDateTime was set to 2017-07-04T06:00.
To control the output, you can either do:
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Which will output the LocalDateTime as 2017-07-04T06:00:00, or you can use a custom formatter:
LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS a"));
module.addSerializer(LocalDateTime.class, serializer);
The serializer above will output the field as 2017-07-04T06:00:00.000 AM. Please note that the Z pattern will not work because a LocalDateTime has no timezone information and it can't resolve its offset - because when you deserialized to a LocalDateTime, the offset information in the input (+01:00) was lost.
Another alternative (without the need to configure the object mapper) is to use the correct pattern in the annotation:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS[xxx]")
private LocalDateTime time;
Note that I used the pattern [xxx] because the offset (+01:00) can be optional: when deserializing, this information is lost becase a LocalDateTime has no information about timezones and offsets, so when serializing this field won't be found - making the field optional (using [] delimiters) make it work for both deserialization and serialization.
This will deserialize the input 2017-07-04T06:00:00.000+01:00 and serialize to 2017-07-04T06:00:00.000 (note that the optional offset is not used in serialization, as the LocalDateTime has no such information).
If you want different formats for deserialization and serialization, you can also create custom classes and anotate them in the field:
public class CustomDeserializer extends LocalDateTimeDeserializer {
public CustomDeserializer() {
super(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
}
public class CustomSerializer extends LocalDateTimeSerializer {
public CustomSerializer() {
super(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS a"));
}
}
// in this case, don't use #JsonFormat
#JsonSerialize(using = CustomSerializer.class)
#JsonDeserialize(using = CustomDeserializer.class)
private LocalDateTime time;
This will use the format 2017-07-04T06:00:00.000+01:00 for deserialize and the format 2017-07-04T06:00:00.000 AM to serialize.

Jackson date format with #JsonFormat?

I want to serialize certain Calendar fields of a POJO with a specific format.
with no annotations, fields like this:
private Calendar timestamp1;
private Calendar timestamp2;
produce JSON like this:
{ ..., timestamp1: 1402402106000, timestamp2: 1402488595000, ... }
I would to add a field formatted as a string as it actually represents a Day as a 24-hour unit, not a specific instant of time. But when I add a new field with an annotation:
#JsonFormat(pattern = "yyyy-MM-dd")
private Calendar oneDay;
I was hoping to get JSON like this:
{ ..., timestamp1: 1402402106000, timestamp2: 1402488595000, oneDay: "2014-06-12", ... }
Instead, I got a the following exception:
com.fasterxml.jackson.databind.JsonMappingException:
Cannot format given Object as a Date
(through reference chain: java.util.HashMap["data"]->java.util.ArrayList[0]-myPojo["oneDay"])
What am I doing wrong?
I'm using Jackson 2.2.0
Here's what I've used: #JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
That works for me.

Categories

Resources