找不到类型为java.util.Date的Json反序列化器

时间:2012-11-23 21:54:27

标签: scala playframework

我正在处理以下代码行。

val list = Car.getNames()
Ok(Json.toJson(list))

我收到了以下错误....

  

[error] my_app / app / models / Car.scala:51:找不到类型为java.util.Date的Json反序列化程序。尝试为此类型实现隐式读取或格式。

Carjava.util.date个对象作为参数之一,我实现了读取写入以支持java.util.date对象,因为import play.api.libs.json.*不支持。

你会指出我的错误吗?

implicit object CarFormat extends Format[Car] {

    def reads(json: JsValue): Car = Car(
      (json \ "id").as[Long],
      (json \ "height").as[Double],
      (json \ "weight").as[Double],
      (json \ "date").asOpt[java.util.Date]
    )   

    def writes(car: Car) = 
        JsObject(
            Seq(
                "id" -> JsString(car.id.toString),
                "height" -> JsString(car.height.toString),
                "weight" -> JsString(car.weight.toString),
                "date" -> JsString(car.date.toString)
            )   
        )   
}   

1 个答案:

答案 0 :(得分:11)

您只为Format定义了Car,但Format需要java.util.Date。试试这个:

import play.api.libs.json._

case class Car(id:Long, height:Double, weight:Double, date:Option[java.util.Date])

implicit object CarFormat extends Format[Car] {

  implicit object DateFormat extends Format[java.util.Date] {
    val format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    def reads(json:JsValue): java.util.Date = format.parse(json.as[String])
    def writes(date:java.util.Date) = JsString(format.format(date))
  }

  def reads(json: JsValue): Car = Car(
    (json \ "id").as[Long],
    (json \ "height").as[Double],
    (json \ "weight").as[Double],
    (json \ "date").asOpt[java.util.Date]
  )   

  def writes(car: Car) = 
    JsObject(
        Seq(
            "id" -> JsString(car.id.toString),
            "height" -> JsString(car.height.toString),
            "weight" -> JsString(car.weight.toString),
            "date" -> JsString(car.date.toString)
        )   
    )   
}