Created
January 9, 2015 18:51
-
-
Save edgarmueller/584c3d1faa933a4cb568 to your computer and use it in GitHub Desktop.
Json writes for a superclass in scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait PropertyType { | |
def price: Double | |
} | |
case class House(price: Double, noOfBedRooms: Option[Short]) extends PropertyType | |
case class Land(price: Double, area: Option[Double]) extends PropertyType | |
object House { | |
implicit val houseReads: Reads[House] = ( | |
(JsPath \ "price").read[Double] and | |
(JsPath \ "noOfBedRooms").readNullable[Short] | |
)(House.apply _) | |
implicit val houseWrites: Writes[House] = new Writes[House] { | |
override def writes(house: House): JsValue = Json.obj( | |
"price" -> house.price, | |
"noOfBedRooms" -> house.noOfBedRooms, | |
"type" -> "House" | |
) | |
} | |
} | |
object Land{ | |
implicit val landReads: Reads[Land] = ( | |
(JsPath \ "price").read[Double] and | |
(JsPath \ "area").readNullable[Double] | |
)(Land.apply _) | |
implicit val landWrites: Writes[Land] = new Writes[Land] { | |
override def writes(land: Land): JsValue = Json.obj( | |
"price" -> land.price, | |
"area" -> land.area, | |
"type" -> "Land" | |
) | |
} | |
} | |
case class Property(owner: String, propertyType: PropertyType) | |
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] = { | |
((__ \ "type").read[String] and __.json.pick).tupled flatMap { case (t, js) => t match { | |
case "Land" => Reads { _ => Json.fromJson[Land](js)} map { c => c: PropertyType} | |
case "House" => Reads { _ => Json.fromJson[House](js)} map { c => c: PropertyType} | |
}} | |
} | |
implicit val format = Json.format[Property] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment