我有一个特征/案例类设置,如:
sealed trait Vehicle
case class Honda(...) extends Vehicle
case class Toyota(...) extends Vehicle
case class VehicleSet(bestSeller: Vehicle, others: Seq[Vehicle])
当我为VehicleSet写入读取时,它正在说
"No Json deserializer found for type Vehicle. Try to implement an implicit reads or Format this type"
object VehicleJsonFormats {
implicit val hondaWrites ...
implicit val toyotaWrites ...
implicit val vehicleSetWrites ...
implicit val hondaReads ...
implicit val tototaReads ...
implicit val vehicleSetReads: Reads[VehicleSet] = (
(JsPath \ "bestSeller").read[Vehicle] and
(JsPath \ "other").read[Seq[Vehicle]]
) (VehicleSet.apply _)
}
我很困惑这会如何与Trait一起使用?
答案 0 :(得分:0)
您需要Reads[Vehicle]
之类的内容:
implicit val vehicleReads: Reads[Vehicle] = Reads[Vehicle] {
case json: JsObject =>
(json \ "make").asOpt[String] match {
case Some("Honda") => hondaReads.reads(json)
case Some("Toyota") => toyotaReads.reads(json)
case _ => JsError("Vehicle expected")
}
case _ => JsError("JsObject expected")
}