1

I've got some JSON that has timestamps in milliseconds:

{"foo":"bar","timestamp":1386280997}

Asking Jackson to deserialize this into an object with a DateTime field for the timestamp results in 1970-01-17T01:11:25.983Z, a time shortly after the epoch because Jackson is assuming it to be in nanoseconds. Aside from ripping apart the JSON and adding some zeros, how might I get Jackson to understand the millisecond timestamp?

Edit—some test code that shows this (Groovy syntax):

class TimestampThing {
    DateTime timestamp

    @JsonCreator
    public TimestampThing(@JsonProperty('timestamp') DateTime timestamp) {
      this.timestamp = timestamp
    }
}

And a couple of tests, the first in milliseconds, the second in microseconds:

class TimestampTest extends GroovyTestCase {
    private ObjectMapper mapper = new ObjectMapper()

    void testMillisecondTimestamp() {
        String json = '{"timestamp":1386280997}'
        TimestampThing thing = mapper.readValue(json, TimestampThing.class)
        println thing.getTimestamp()
    }

    void testNanosecondTimestamp() {
        String json = '{"timestamp":1386280997000}'
        TimestampThing thing = mapper.readValue(json, TimestampThing.class)
        println thing.getTimestamp()
    }
}

The out from running the test class is:

1970-01-16T20:04:40.997-05:00
2013-12-05T17:03:17.000-05:00
Drew Stephens
  • 17,207
  • 15
  • 66
  • 82
  • 2
    Deserializing JSON dates: "Numeric (integer) serializations are recognized, assumed to be in Unix timestamp notation (milliseconds since epoch, Jan 1st 1970 GMT)" -[Jackson FAQ Date Handling](http://wiki.fasterxml.com/JacksonFAQDateHandling). It doesn't mention nanosecond in there. In fact, `console.log(new Date().getTime())` will show that your timestamp is off by a factor of 1000 in the wrong direction. In other words, that is *seconds* since epoch. – Travis J Dec 16 '13 at 23:38
  • I see your skepticism from reading the FAQ…so I wrote some test code as simple as possible that illustrates the problem for me on Java 1.7.0_21 with Jackson 2.3.0 and Joda Time 2.3 – Drew Stephens Dec 17 '13 at 02:21
  • Whoops! I was off by a few orders of magnitude—the timestamps that I have are in _seconds_ (i.e. Unix timestamps) not _milliseconds_ as I had claimed. So Jackson is indeed doing the correct thing and in line with its documentation. I created a [new question](http://stackoverflow.com/questions/20635698/how-do-i-deserialize-timestamps-that-are-in-seconds-with-jackson) to figure out how to get Jackson to understand my _seconds_ timestamps. – Drew Stephens Dec 17 '13 at 13:40

0 Answers0