Created
June 23, 2019 18:16
-
-
Save AbuCarlo/cca8b3632ff5d119028644a38feda84a to your computer and use it in GitHub Desktop.
Jackson Serialization of Temporal Types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grapes([ | |
@Grab(group='com.fasterxml.jackson.core', module='jackson-core', version='2.9.9'), | |
@Grab(group='com.fasterxml.jackson.datatype', module='jackson-datatype-jsr310', version='2.9.9') | |
] | |
) | |
import java.time.* | |
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule | |
import com.fasterxml.jackson.databind.ObjectMapper | |
import com.fasterxml.jackson.databind.SerializationFeature | |
// Seee https://github.com/FasterXML/jackson-modules-java8 | |
// See https://github.com/FasterXML/jackson-modules-java8/tree/master/datetime | |
@groovy.transform.ToString | |
class Pojo { | |
Instant instant | |
OffsetDateTime zdt | |
} | |
final def jsonWithIso = '{ "instant": "2019-06-21T18:16:07.857Z", "zdt": "2019-06-21T18:16:07.857Z" }' | |
final def jsonWithNs = '{ "instant": 1561141090.164000000, "zdt": 1561141090.164000000 }' | |
def badMapper = new ObjectMapper() | |
// These will fail! | |
// badMapper.readValue(jsonWithNs, Pojo) | |
// badMapper.readValue(jsonWithIso, Pojo) | |
def pojo = new Pojo(instant: Instant.now(), zdt: OffsetDateTime.now()) | |
println "Groovy generates a toString() method: $pojo\n" | |
def badJson = badMapper.writerWithDefaultPrettyPrinter().writeValueAsString(pojo) | |
// This will also fail: Jackson can't read in the value it's written. | |
// badMapper.readValue(badJson, Pojo) | |
// The Groovy console will print out the default Java representation of the timestamp. | |
// This has nothing to do with JSON. Note that an Instant has no time zone: epoch | |
// time is measured relative to UTC. | |
println "Default (bad) serialization of Java temporal types: $badJson" | |
println() | |
def mapper = new ObjectMapper() | |
mapper.registerModule(new JavaTimeModule()) | |
// mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, true) | |
// mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) | |
println mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pojo) | |
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) | |
println mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pojo) | |
println mapper.readValue(jsonWithIso, Pojo) | |
println mapper.readValue(jsonWithNs, Pojo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment