【问题标题】:How to write a reads method of a trait如何编写特征的读取方法
【发布时间】:2016-10-08 00:26:33
【问题描述】:

我有一个特征/案例类设置,例如:

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 一起工作?

【问题讨论】:

  • 你有没有尝试在 Object VehicleSet 中编写隐式读取器?
  • @HendrikT 隐式阅读器是什么,车辆特性?
  • 是的,您需要为您的车辆创建一个阅读器:implicit val vehicleReads: Reads[Vehicle] = ???。您将需要一些代码来获取您的 json 并将其转换为您的车辆实例:HondaToyota。这将取决于您如何将车辆与 json 对象区分开来。
  • @vdebergue 但车辆是一种特征。我已经对本田和丰田进行了隐式阅读。

标签: scala playframework


【解决方案1】:

您需要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")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 2023-04-10
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多