40

I've got some JSON that has timestamps in seconds (i.e. a Unix timestamp):

{"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 milliseconds. Aside from ripping apart the JSON and adding some zeros, how might I get Jackson to understand the seconds timestamp?

Drew Stephens
  • 17,207
  • 15
  • 66
  • 82
  • 3
    There's a question [here](http://stackoverflow.com/questions/5591967/jackson-date-deserialization) that shows how to implement a custom date deserialization class – Slicedpan Dec 17 '13 at 13:42
  • Thanks for the tip—I answered the question with the details of how I solved this issue since the deserializer is a bit different from that question. – Drew Stephens Dec 17 '13 at 15:30

4 Answers4

33

I wrote a custom deserializer to handle timestamps in seconds (Groovy syntax).

class UnixTimestampDeserializer extends JsonDeserializer<DateTime> {
    Logger logger = LoggerFactory.getLogger(UnixTimestampDeserializer.class)

    @Override
    DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String timestamp = jp.getText().trim()

        try {
            return new DateTime(Long.valueOf(timestamp + '000'))
        } catch (NumberFormatException e) {
            logger.warn('Unable to deserialize timestamp: ' + timestamp, e)
            return null
        }
    }
}

And then I annotated my POGO to use that for the timestamp:

class TimestampThing {
    @JsonDeserialize(using = UnixTimestampDeserializer.class)
    DateTime timestamp

    @JsonCreator
    public TimestampThing(@JsonProperty('timestamp') DateTime timestamp) {
        this.timestamp = timestamp
    }
}
Drew Stephens
  • 17,207
  • 15
  • 66
  • 82
  • Hello, just out of curiousity what dialect of Java is it? Thanks! – tuscland Oct 10 '15 at 12:45
  • Works like a charm in ordinary boring java, too. Just use the Annotation on whatever DateTime field you need. Did not try using Java 8 Date, but should be no problem there either. Thanks – thomi Oct 10 '15 at 15:10
  • 12
    If you can use java8 you're maybe interested in using `java.time.Instant` class and to use regular jackson [datatypes](https://github.com/FasterXML/jackson-modules-java8/). This way you just need `@JsonProperty("timestamp") private Instant timestamp` – Pierrick Mar 20 '17 at 12:17
  • @Pierrick Please turn this into an answer, so I can upvote ;-) – lilalinux Mar 15 '18 at 10:45
  • @Pierrick I am using `java.time.Instant`, and Jackson still treats timestamps as milliseconds. – Harold L. Brown Aug 26 '22 at 07:55
16
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="s")
public Date timestamp;

edit: vivek-kothari suggestion

@JsonFormat(shape=JsonFormat.Shape.NUMBER, pattern="s")
public Timestamp timestamp;
sherpya
  • 4,890
  • 2
  • 34
  • 50
14

A very similar approach to that of @DrewStephens's which uses the Java SE TimeUnit API (introduced in JDK1.5) instead of plain String concatenation and is thus (arguably) a little bit cleaner and more expressive:

public class UnixTimestampDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser parser, DeserializationContext context) 
            throws IOException, JsonProcessingException {
        String unixTimestamp = parser.getText().trim();
        return new Date(TimeUnit.SECONDS.toMillis(Long.valueOf(unixTimestamp)));
    }
}

Specifying your custom deserializer (UnixTimestampDeserializer) on the affected Date field(s):

@JsonDeserialize(using = UnixTimestampDeserializer.class)
private Date updatedAt;
Priidu Neemre
  • 2,813
  • 2
  • 39
  • 40
1

I had this exact issue, except my ZonedDateTime objects got turned to unix-timestamps (seconds) and I needed them in milliseconds (to initialize JS Date objects on the browser).

Implementing a custom serializer/deserializer looked like too much work for something that should be pretty straightforward, so I looked elsewhere and found that I can just configure the object mapper for the desired result.

Because my application already overrides the default ObjectMapper provided by Jersey, I just had to disable SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS.

Here's my code

@Provider
public class RPObjectMapperProvider implements ContextResolver<ObjectMapper> {

    final ObjectMapper defaultObjectMapper;

    public RPObjectMapperProvider() {
        defaultObjectMapper = new ObjectMapper();

        // this turned ZonedDateTime objects to proper seconds timestamps 
        defaultObjectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // disable to serialize dates for millis timestamps
        defaultObjectMapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);

        // using Java8 date time classes
        defaultObjectMapper.registerModule(new JavaTimeModule());
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return defaultObjectMapper;
    }
}

And that's it

svarog
  • 9,477
  • 4
  • 61
  • 77