Search code examples
scalaplayframeworkplay-json

formatters for List[DateTime] play scala


I am working on a project using Play, Scala, MongoDB. I want to store the List[Datetime] in a collection, so I need fomatters for it. To store the Datetime I used this formatter

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)
}

but for storing list of datetimes it is not working. thanks in advance for help


Solution

  • You need to create an implicit json Writer and Reader for the List[DateTime]. In your example, you are only defining how to serialize and deserialize the DateTime type. Adding this below the formatter should make the framework know how to JSONify DateTime lists. See working example below:

      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())