List[DateTime] play scala 的格式化程序

formatters for List[DateTime] play scala

我正在使用 Play、Scala 开发一个项目,MongoDB。我想将 List[Datetime] 存储在一个集合中,所以我需要 fomatters。为了存储 Datetime 我使用了这个格式化程序

implicit def dateFormat = {
  val dateStandardFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"

  val dateReads: Reads[DateTime] = Reads[DateTime](js =>
    js.validate[JsObject].map(_.value.toSeq).flatMap {
      case Seq(("$date", JsNumber(ts))) if ts.isValidLong =>
        JsSuccess(new DateTime(ts.toLong))
      case _ =>
        JsError(__, "validation.error.expected.$date")
    }
  )

  val dateWrites: Writes[DateTime] = new Writes[DateTime] {
    def writes(dateTime: DateTime): JsValue = Json.obj("$date"-> dateTime.getMillis())
  }

  Format(dateReads, dateWrites)
}

但是对于存储日期时间列表它不起作用。在此先感谢您的帮助

您需要为 List[DateTime] 创建隐式 json Writer 和 Reader。在您的示例中,您仅定义如何序列化和反序列化 DateTime 类型。在格式化程序下面添加它应该使框架知道如何 JSONify DateTime 列表。 请参阅下面的工作示例:

  val dateStandardFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"

  val dateReads: Reads[DateTime] = Reads[DateTime](js =>
    js.validate[JsObject].map(_.value.toSeq).flatMap {
      case Seq(("$date", JsNumber(ts))) if ts.isValidLong =>
        JsSuccess(new DateTime(ts.toLong))
      case _ =>
        JsError(__, "validation.error.expected.$date")
    }
  )

  val dateWrites: Writes[DateTime] = new Writes[DateTime] {
    def writes(dateTime: DateTime): JsValue = Json.obj("$date" -> dateTime.getMillis())
  }

  implicit def dateFormat = Format(dateReads, dateWrites)

  implicit val listDateTimeFormat = Format(Reads.list[DateTime](dateReads), Writes.list[DateTime](dateWrites))

  val m = List(DateTime.now(), DateTime.now(), DateTime.now(), DateTime.now(), DateTime.now())

  println(Json.toJson(m).toString())

您可以使用此项目中的 MongoDateFormats simple-reactivemongo