Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

java - How to store Date field as ISODate() using jackson in MongoDb

I am trying to persist a java object having java.util.Date field in mongo collection using fasterxml jackson. The problem is the default nature of objectMapper is to store Date as NumberLong type.

For e.g , a createdTime field of java.util.Date type gets stored as below:

"createdTime" : NumberLong("1427728445176")

I want to store it in ISODate format which is available in mongo Shell.

Now, i know there is way to format object mapper to store Date in a String dateformat. But I am ONLY looking for ISODate() format.

For e.g "createdTime" : ISODate("2015-01-20T16:39:42.132Z")

Is there a way to do that ? Please advise gurus . Thanks in advance for help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you need is the Jackson Joda Module. If you import that into your classpath, you can do the following on your mapper to write it as your desired Timestamp:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
mapper.writeValueAsString(date);

You can replace date in the code sample above with your POJO as necessary.

Edit: It looks like what you really want is a custom serializer. That would look something like this:

public class IsoDateSerializer extends JsonSerializer<DateTime> {
    @Override
    public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) {
        String isoDate = ISODateTimeFormat.dateTime().print(value);
        jgen.writeRaw("ISODATE("" + isoDate + "")");
    }

Then you'll either register it on the mapper for all DateTime types

mapper.addSerializer(DateTime.class, new IsoDateSerializer());

or specify it on the function using annotations

@JsonSerializer(using = IsoDateSerializer.class)
public DateTime createdTime;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...