No Json deserializer found for type java.util.Date

playframework, scala

Solution

You only defined `Format` for `Car` but it requires a `Format` for `java.util.Date`. Try this:

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

Problem

I'm working on the following lines of code. ``` val list = Car.getNames() Ok(Json.toJson(list)) ``` I got the following errors.... [error] my_app/app/models/Car.scala:51: No Json deserializer found for type java.util.Date. Try to implement an implicit Reads or Format for this type. `Car` has `java.util.date` object as one of parameters and I implemented the Reads and Writes to support the `java.util.date` object since `import play.api.libs.json.*` does not support it. Would you point my mistakes? ``` 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) ) ) } ```

Original source