ligboo
ligboo

Reputation: 11

Jackson date format with @JsonFormat?

I want to serialize certain Calendar fields of a POJO with a specific format.

with no annotations, fields like this:

private Calendar timestamp1;
private Calendar timestamp2;

produce JSON like this:

{ ..., timestamp1: 1402402106000, timestamp2: 1402488595000, ... }

I would to add a field formatted as a string as it actually represents a Day as a 24-hour unit, not a specific instant of time. But when I add a new field with an annotation:

@JsonFormat(pattern = "yyyy-MM-dd")
private Calendar oneDay;

I was hoping to get JSON like this:

{ ..., timestamp1: 1402402106000, timestamp2: 1402488595000, oneDay: "2014-06-12", ... }

Instead, I got a the following exception:

com.fasterxml.jackson.databind.JsonMappingException: 
    Cannot format given Object as a Date 
    (through reference chain: java.util.HashMap["data"]->java.util.ArrayList[0]-myPojo["oneDay"])

What am I doing wrong?

I'm using Jackson 2.2.0

Upvotes: 1

Views: 24939

Answers (1)

Jonathan Larson
Jonathan Larson

Reputation: 302

Here's what I've used: @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")

That works for me.

Upvotes: 7

Related Questions