无法在Mongodb中序列化LocalDate

我正在使用Java 8 java.time.LocalDate来解析日期。

但是尝试将LocalDate对象插入到mongodb中。我在Java驱动程序中收到错误:

private def writeData(measure: DBCollection, installation: Int, date: String, dates: ListBuffer[LocalDate],

values: ListBuffer[BigDecimal], validated: Boolean, overwrite: Boolean) {

val timeValues: BasicDBList = new BasicDBList

var i = 0

while ( i < dates.size ) {

val obj: BasicDBObject = new BasicDBObject("time", dates(i))

obj.put("value", values(i).toString())

timeValues.add(obj)

i += 1

}

if ( debug ) System.out.println("Storedata: " + timeValues.toString) <-- error here

错误日志:

java.lang.RuntimeException:json无法序列化类型:com.mongodb.util.JSONSerializers $

MapSerializer.serialize(JSONSerializers)上com.mongodb.util.ClassMapBasedObjectSerializer.serialize(ClassMapBasedObjectSerializer.java:77)的类java.time.LocalDate

.java:317)com.mongodb.util.ClassMapBasedObjectSerializer.serialize(ClassMapBasedObjectSerializer.java:79)com.mongodb.util.JSONSerializers

$

IterableSerializer.serialize(JSONSerializers.java:290)com.mongodb.util.ClassMapBased

com.mongodb.util.JSON.serialize(JSON.java:54)处com.mongodb.util.JSON.serialize(JSON.java:40)处com.mongodb.BasicDBList.toString处的serialize(ClassMapBasedObjectSerializer.java:79)

(web.MeasureAccess.writeData(MeasureAccess.scala:203)的web.MeasureAccess。(BasicDBList.java:38)。Web上的firstTime(MeasureAccess.scala:52)。web.MeasureAccess.main(MeasureAccess.scala:262)在sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Method)在web.MeasureAccess.main(MeasureAccess.scala)在sun.reflect。

com.intellij.rt.execution处java.lang.reflect.Method.invoke(Method.java:483)上的sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)上的NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

.application.AppMain.main(AppMain.java:134)DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43),位于com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)上的java.lang.reflect.Method.invoke(Method.java:483)DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43),位于com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)上的java.lang.reflect.Method.invoke(Method.java:483)

我正在使用mongo-java-driver-2.13.0-rc1.jar Scala 2.11.4和Java 1.8.0_25

为了完整性。

回答:

不幸的是,MongoDB驱动程序使用该java.util.Date类型,请参见此处的文档

因此,您必须首先将LocalDate转换为Date实例,例如:

MongoClient mongoClient = new MongoClient("localhost", 27017);

DB db = mongoClient.getDB("test");

DBCollection coll = db.getCollection("testcol");

LocalDate ld = LocalDate.now();

Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();

Date date = Date.from(instant);

BasicDBObject doc = new BasicDBObject("localdate", date);

coll.insert(doc);

我建议使用类似吗啡或Jongo包裹MongoDB的驱动程序,虽然,以含蓄做对飞这些转换,您可以注册全球映射器,这样就可以使用LOCALDATE的,等等,在你的领域模型

以上是 无法在Mongodb中序列化LocalDate 的全部内容, 来源链接: utcz.com/qa/399808.html

回到顶部