No Json deserializer for type java.util.Date

I am 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: There is no Json desancializer for type java.util.Date. Try to implement implicit reads or a format for this type.

Car has a java.util.date object as one of the parameters, and I implemented Reads and Writes to support the java.util.date object since import play.api.libs.json.* Does not support it.

Could you indicate 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) ) ) } 
+8
scala playframework
source share
1 answer

You define Format for Car , but java.util.Date requires Format . Try the following:

 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) ) ) } 
+11
source share

All Articles