2014-12-24 2 views
2
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)) 

}JSON은 스칼라의 슈퍼 클래스에 대한 기록

case class Property(owner: String, propertyType: PropertyType)<--- 

PropertyType이 2 subclases 하우스와 토지 내가 모두 하우스를 사용할 수 있도록 내가 속성에 대한 작가를 구현할 수있는 방법

object Property{ 

    implicit val propertyWrites: Writes[Property] = (
    (JsPath \ "owner").write[String] and 
    (JsPath \ "propertyType").write[PropertyType] <--- 
)(unlift(Property.unapply)) 

} 

및 토지 객체를 PropertyType으로 사용 하시겠습니까 ??

답변

1

당신은 당신의 Property 객체 내 PropertyType에 대한 Writes 인스턴스를 제공 할 수있는, 그 패턴은 실제의 형태가 쓸 수 일치 :

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

+0

에 대한 인스턴스를 읽고 대답. – edi

+0

옵션 [fieldName]을 사용하는 경우 서브 클래스의 유형을 결정할 수 없으며 예상대로 읽기 및 쓰기가 작동하지 않습니다. 여기에서 길을 잃었습니다. – user123123

+0

옵션 [fieldName]은 무엇을 의미합니까? 관련 코드를 게시 할 수 있습니까? – edi