Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Json deserializer found for type java.util.Date

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)
            )   
        )   
}   
like image 592
Masashi Avatar asked Nov 23 '12 21:11

Masashi


1 Answers

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)
        )   
    )   
}   
like image 62
xiefei Avatar answered Nov 03 '22 04:11

xiefei