我正在处理以下代码行。
val list = Car.getNames()
Ok(Json.toJson(list))
我收到了以下错误....
[error] my_app / app / models / Car.scala:51:找不到类型为java.util.Date的Json反序列化程序。尝试为此类型实现隐式读取或格式。
Car
将java.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)
)
)
}
答案 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)
)
)
}