Json在scala中写了一个超类

时间:2014-12-24 06:21:58

标签: json scala

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 ??

1 个答案:

答案 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

添加了读取实例