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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With