8

我有 joda Datetime 字段的案例类:

case DomainPositionData(domain: String, position: Int, change: Option[Int], date:DateTime)

尝试使用宏生成读写器:

implicit val domPosFormat = Macros.handler[DomainPositionData]

我有:

Implicit org.joda.time.DateTime for 'value date' not found

但我还没有找到如何实现我自己的隐式转换器的信息。

4

3 回答 3

16

查看现有处理程序的源代码,您可以尝试创建这样的隐式转换(未测试):

import org.joda.time.DateTime

implicit object BSONDateTimeHandler extends BSONHandler[BSONDateTime, DateTime] {
  def read(time: BSONDateTime) = new DateTime(time.value)
  def write(jdtime: DateTime) = BSONDateTime(jdtime.getMillis)
}
于 2013-05-21T13:14:30.637 回答
2

另一种方法是使用新的 BSONReader 和 BSONWriter(在 0.9 中有 2 个类型参数):

implicit object DatetimeReader extends BSONReader[BSONDateTime, DateTime]{
    def read(bson: BSONDateTime): DateTime = new DateTime(bson.value)
}

implicit object DatetimeWriter extends BSONWriter[DateTime, BSONDateTime]{
    def write(t: DateTime): BSONDateTime = BSONDateTime(t.getMillis)
}
于 2013-05-22T16:52:24.163 回答
0

对于版本 1.0.x

  implicit object DateTimeReader extends BSONReader[DateTime] {
    def readTry(bson: BSONValue): Try[DateTime] =  bson match {
      case time: BSONDateTime => Success(new DateTime(time.value))
      case _ => Failure(new IllegalArgumentException())
    }
  }

  implicit object DateTimeWriter extends BSONWriter[DateTime]{
    override def writeTry(t: DateTime): Try[BSONValue] = Try{
      BSONDateTime(t.getMillis)
    }
  }

或与 val

  implicit val dateTimeReader: BSONReader[DateTime] = BSONReader[DateTime]{
    case  t: BSONDateTime => new DateTime(t.value)
  }

  implicit val dateTimeWriter: BSONWriter[DateTime] = BSONWriter[DateTime]{ time =>
    BSONDateTime(time.getMillis)
  }
于 2021-08-25T16:57:25.417 回答