Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize java.time.ZoneId using Jackson in Spring Boot

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
private LocalDateTime accessStart;

private ZoneId accessStartZoneId;

Is there a built-in pattern mapper in Jackson to map JSON request containing a java ZoneId?

{
  "accessStart": "2017-10-10T10:10:10.100",
  "accessStartZoneID": "Australia/Sydney"
}

I'm using Spring Boot 1.5.4.RELEASE. How to configure the deserializer for ZoneId? It works well with accessStart

JSON parse error: Can not construct instance of java.time.ZoneId: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

like image 857
letthefireflieslive Avatar asked Dec 07 '25 08:12

letthefireflieslive


1 Answers

A step back

I'm particularly curious to know why you are using LocalDateTime along with ZoneId. Wouldn't it be easier to use only ZonedDateTime?

In terms of design, ZonedDateTime is a combination of a LocalDateTime and a ZoneId.

Supporting ZoneId

Assuming that you still want to use ZoneId, you can write your own custom (de)serializer.

Alternatively, you can add the jackson-datatype-jsr310 artifact to your dependencies:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9</version>
</dependency>

And then register the JavaTimeModule module in your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

In a Spring Boot application, you need the following:

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper createObjectMapper() {  
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return mapper;
    }
}

ZoneId is supported according to the documentation:

  • ZoneId and ZoneOffset, which do not actually store dates and times but are supported with this module nonetheless.
like image 90
cassiomolin Avatar answered Dec 10 '25 14:12

cassiomolin



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!