ozgus
ozgus

Reputation: 179

oData Date format with Jackson ObjectMapper

I want jackson to parse date to the following format:

/Date(1413072000000)/

How can I do that with Jackson ObjectMapper? I tried setDateFormat and SimpleDateFormat, but inside that method I couldn't set miliseconds to appear.

Upvotes: 2

Views: 1352

Answers (1)

hexin
hexin

Reputation: 977

You can define your own DateFormat, like that:

public class MyDateFormat extends DateFormat {

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return toAppendTo.append(String.format("/Date(%d)/", date.getTime()));
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object clone() {
        return new MyDateFormat();
    }
}

And set the instance of MyDateFormat to ObjectMapper with:

mapper.setDateFormat(new MyDateFormat());

In MyDateFormat class there is added clone() overriden, because Jackson needs to clone our format in case of concurrency issues.

Upvotes: 1

Related Questions