Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring: Jackson deserialization to ZonedDateTime

Assuming the following class I want to use for deserialization from an external JSON payload:

public class MyObject {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    private ZonedDateTime timestamp;

}

When I'm trying to consume the JSON payload, Jackson throws the following error:

Cannot deserialize value of type `java.time.ZonedDateTime` from String "2019-01-23T12:54:18.610Z": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '2019-01-23T12:54:18.610Z' could not be parsed at index 23

As you can see, the incoming string is "2019-01-23T12:54:18.610Z", which is a valid ZonedDateTime as I understand it. Using jshell, parsing that string into a ZonedDateTime using ZonedDateTime.parse("2019-01-23T12:54:18.610Z") results in a valid ZonedDateTime as I would expect.

  • Why is Jackson failing here?
  • What can I do to make it work?

I'm not an expert on Spring or Jackson, either. Thanks.

Edit: I'm using Spring Boot v2.1.1.RELEASE.

like image 345
J.P. Avatar asked Jun 01 '26 20:06

J.P.


2 Answers

The Z in the pattern won't accept a literal 'Z' in the value, using X instead should work:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")

The pattern is specified as a Java SimpleDateFormat - Java 10 reference here.

like image 165
mids Avatar answered Jun 03 '26 09:06

mids


You shoud replace Z with X, like yyyy-MM-dd'T'HH:mm:ss.SSSX.

See the doc:

Symbol  Meaning                     Presentation      Examples
X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
Z       zone-offset                 offset-Z          +0000; -0800; -08:00;
like image 45
xingbin Avatar answered Jun 03 '26 10:06

xingbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!