如何使用MongoDb中的jackson将Date字段存储为ISODate() [英] How to store Date field as ISODate() using jackson in MongoDb
问题描述
我正在尝试使用fasterxml jackson在mongo集合中持久保存具有 java.util.Date
字段的java对象。
问题是objectMapper的默认性质是将Date存储为NumberLong类型。
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.
例如, createdTime
字段 java.util.Date
类型存储如下:
For e.g , a createdTime
field of java.util.Date
type gets stored as below:
createdTime:NumberLong(1427728445176)
"createdTime" : NumberLong("1427728445176")
我想将它存储在mongo Shell中可用的 ISODate 格式。
I want to store it in ISODate format which is available in mongo Shell.
现在,我知道有办法格式化对象映射器以字符串dateformat存储日期。
但我只是在寻找ISODate()格式。
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.
例如
createdTime:ISODate (2015-01-20T16:39:42.132Z)
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.
推荐答案
您需要的是 Jackson Joda模块。如果将其导入到类路径中,则可以在映射器上执行以下操作,将其写为所需的时间戳:
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);
您可以在代码示例中替换 date
如果需要,请使用您的POJO。
You can replace date
in the code sample above with your POJO as necessary.
编辑:
看起来您真正想要的是自定义序列化程序。这看起来像这样:
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 + "\")");
}
然后你要在映射器上注册所有DateTime类型
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;
这篇关于如何使用MongoDb中的jackson将Date字段存储为ISODate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!