trait PropertyType {
def price: Double
}
case class House(price: Double, noOfBedRooms: Short) extends PropertyType
object House{
implicit val houseReads: Reads[House] = (
(JsPath \ "price").read[Double] and
(JsPath \ "noOfBedRooms").read[Short]
)(House.apply _)
implicit val houseWrites: Writes[House] = (
(JsPath \ "price").write[Double] and
(JsPath \ "noOfBedRooms").write[Short]
)(unlift(House.unapply))
implicit val format = Format(houseReads,houseWrites)
}
case class Land(price: Double,area: Double) extends PropertyType
object Land{
implicit val landWrites: Writes[Land] = (
(JsPath \ "price").write[Double] and
(JsPath \ "area").write[Double]
)(unlift(Land.unapply))
}
case class Property(owner: String, propertyType: PropertyType)<---
PropertyType有2个子栏目House和Land
object Property{
implicit val propertyWrites: Writes[Property] = (
(JsPath \ "owner").write[String] and
(JsPath \ "propertyType").write[PropertyType] <---
)(unlift(Property.unapply))
}
我如何实现属性的Writer,以便我可以将House和Land对象用作PropertyType ??
答案 0 :(得分:1)
您可以在Writes
对象中为PropertyType
提供Property
个实例,该模式与要写入的实际类型相匹配:
object Property {
implicit object PropertyTypeWrites extends Writes[PropertyType] {
override def writes(pt: PropertyType): JsValue = pt match {
case l: Land => Json.toJson(l)(Land.landWrites)
case h: House => Json.toJson(h)(House.houseWrites)
}
}
implicit val propertyTypeReads: Reads[PropertyType] =
JsPath.read[Land].map(x => x: PropertyType) orElse
JsPath.read[House].map(x => x: PropertyType)
implicit val propertyWrites: Writes[Property] = ...
}
编辑:为PropertyType