How can I use annotations to deserialize Greenwich Time into LocalTime?

29 views
Skip to first unread message

黄瑶

unread,
Jan 21, 2021, 11:42:45 PM1/21/21
to jackson-user

Hello:

How can I use annotations to deserialize Greenwich Time into LocalTime?
Here is Demo class:

public class Demo implements Serializable { private LocalDateTime time; // setter getter ... }

Here is Demo JSON:

{"time" : "2019-05-08T07:45:44.519Z"}

The time I expect to get is 2019-05-08T15:45:44.519, but what I get is: 2019-05-08T07:45:44.519

Now I'm using custom deserialized classes to solve the problem:

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { private static final String ZULU = "Z"; @Override public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { String text = jsonParser.getText(); if (text.endsWith(ZULU)) { return LocalDateTime.ofInstant(Instant.parse(text), ZoneId.systemDefault()); } else { return LocalDateTime.parse(text, DateTimeFormatter.ISO_LOCAL_DATE_TIME); } } } public class Demo implements Serializable { @JsonDeserialize(using = CustomLocalDateTimeDeserializer.class) private LocalDateTime time; // setter getter ... }

Is there any other way?
I would appreciate your help.

Drew Stephens

unread,
Jan 22, 2021, 6:05:23 AM1/22/21
to jackson-user
That timestamp you have (2019-05-08T07:45:44.519Z) is an ISO-8601 instant. If you .register(JavaTimeModule()) (which is provided by jackson-modules-java8) in your ObjectMapper it will be able to deserialize that into a java.time.Instant without any other configuration.  Thereafter, you can convert that into the timezone you

Example in Kotlin:

import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import java.time.Instant

fun main() {
    data class TimeHolder(val time: Instant)

    val objectMapper = jacksonObjectMapper()
        .registerModule(JavaTimeModule())

    val thing = objectMapper.readValue<TimeHolder>("""{"time" : "2019-05-08T07:45:44.519Z"}""")

    println(thing) // TimeHolder(time=2019-05-08T07:45:44.519Z)
    println(thing.time.atZone(ZoneId.of("Asia/Brunei"))) // 2019-05-08T15:45:44.519+08:00[Asia/Brunei]
}

-Drew

黄瑶

unread,
Jan 22, 2021, 8:57:05 PM1/22/21
to jackson-user
thanks
Reply all
Reply to author
Forward
0 new messages