-2

How can I deserialize a LocalDateTime in this format 2023-01-13T08:54:25.83-03:00 using Jackson?

I am tryin to use annotations

@JsonFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss", shape = JsonFormat.Shape.STRING)
@JsonProperty("created_at")
private LocalDateTime createdAt;
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 3
    When you compare the pattern to the value, you should notice there's a difference. – f1sh Jan 13 '23 at 12:03
  • 1
    It seems that your input is not a local date time, but one with an offset. – Hulk Jan 13 '23 at 12:06
  • 2
    Apart from what @f1sh wrote: You have a `String` representation of a date with time and offset from UTC, but a `LocalDateTime` will not be able to store that offset. You should either switch to `OffsetDateTime` or parse and ignore the offset. Yes, the offset is one of the differences, but there's at least one more: fractions of second. – deHaar Jan 13 '23 at 12:06
  • 1
    Take a look at [Jackson Date](https://www.baeldung.com/jackson-serialize-dates). The simplest solution is to change `LocalDateTime` to `OffsetDateTime` - [Jackson: parse custom offset date time](https://stackoverflow.com/questions/46263773/jackson-parse-custom-offset-date-time) – Michał Ziober Jan 13 '23 at 14:35
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jan 13 '23 at 19:18
  • @MichałZiober That is not only simpler, it is also the correct solution. `LocalDateTime` is the wrong class to use for the time when something was created. – Ole V.V. Jan 14 '23 at 13:25

1 Answers1

0

Done, thank you.

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonProperty("created_at")
private LocalDateTime createdAt;

...

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

@Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return OffsetDateTime.parse( p.getText() ).toLocalDateTime();
    }

}
  • 1
    Thanks for answering your own question. I am sorry, you don’t want this. You are deserializing `2023-01-13T08:54:25.83-12:00` and `2023-01-13T08:54:25.83+14:00` into the same `LocalDateTime` value even though they denote points in time that are 26 hours apart, more than a full day. You need the UTC offset from JSON or at least the point in time denoted in the JSON. `LocalDateTime` is the wrong class to use for that. – Ole V.V. Jan 14 '23 at 13:22