3
@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

letthefireflieslive
  • 11,493
  • 11
  • 37
  • 61
  • A `ZoneId` is serialized to its ID (such as `Europe/London`). Are you expecting a different format? How is your JSON requests that contain `ZoneId`? And is there any reason to use a `LocalDateTime` and `ZoneId` separately instead of just using a `ZonedDateTime`? –  Sep 01 '17 at 00:33
  • @Hugo see updates – letthefireflieslive Sep 01 '17 at 00:37

1 Answers1

7

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.
cassiomolin
  • 124,154
  • 35
  • 280
  • 359