Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created March 27, 2011 09:11
Show Gist options
  • Save debasishg/889077 to your computer and use it in GitHub Desktop.
Save debasishg/889077 to your computer and use it in GitHub Desktop.
// class definitions
trait SubUnit
case class Dept(name: String, manager: Employee, subUnits: List[SubUnit]) extends SubUnit
case class Employee(name: String, salary: Double) extends SubUnit
// typeclass instance
object SubUnitProtocol extends DefaultProtocol {
import JsonSerialization._
implicit object SubUnitFormat extends Format[SubUnit] {
def reads(json: JsValue): SubUnit = json match {
case j@JsObject(m) => m.keys.size match {
case 2 => fromjson[Employee](j)
case _ => fromjson[Dept](j)
}
case _ => throw new RuntimeException("JsObject expected")
}
def writes(s: SubUnit): JsValue = s match {
case d: Dept => tojson(d)
case e: Employee => tojson(e)
}
}
}
import SubUnitProtocol._
implicit val DeptFormat: Format[Dept] =
lazyFormat(asProduct3("name", "manager", "subUnits")(Dept)(Dept.unapply(_).get))
implicit val EmployeeFormat: Format[Employee] =
asProduct2("name", "salary")(Employee)(Employee.unapply(_).get)
// test script
describe("Serialization of list of traits") {
val e1 = Employee("Mary G.", 1000)
val e2 = Employee("John P.", 5000)
val e3 = Employee("Peter P.", 5000)
val d1 = Dept("Finance", e1, List(e1, e2))
val d2 = Dept("Accounting", e2, List(e1, e2, e3))
val d3 = Dept("Systems", e2, List(d1, d2))
it ("should serialize") {
fromjson[Dept](tojson(d1)) should equal(d1)
fromjson[Dept](tojson(d3)) should equal(d3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment