问题描述
我正在尝试使用 fastxml 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.
例如,java.util.Date
类型的 createdTime
字段存储如下:
For e.g , a createdTime
field of java.util.Date
type gets stored as below:
"createdTime" : NumberLong("1427728445176")
我想以 mongo Shell 中可用的 ISODate 格式存储它.
I want to store it in ISODate format which is available in mongo Shell.
现在,我知道有办法格式化对象映射器以将日期存储在字符串日期格式中.但我只是在寻找 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 将日期字段存储为 ISODate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!