I'm writing a web service using Scala Play. The functionality is ok but I'm refactoring some parts to make my code more readable and clean.
I've used implicit for each of my entity classes to make them convertable to Json. I've also injected toJson
function to Seq[MyEntityClass]
to be able to make an Json array by calling a single function.
It looks like this:
case class MyModel(id: Option[Int], foo: String, bar: String)
object MyModel {
implicit val writer = Json.writes[MyModel]
implicit val reader: Reads[MyModel] = new Reads[MyModel] {
def reads(json: JsValue): JsResult[MyModel] = {
for {
foo <- (json \ "foo").validate[String]
bar <- (json \ "bar").validate[String]
} yield MyModel(None, foo, bar)
}
}
implicit def richMyModelSeq(apps: Seq[MyModel]) = new {
def toJson:JsValue = Json.toJson(apps)
}
// ...
}
How can I define this code in a super class to not repeat this code for each entity class?
Why this is not working?
abstract class Jsonable {
implicit val writer = Json.writes[Jsonable]
implicit def richMyModelSeq(apps: Seq[MyModel]) = new {
def toJson:JsValue = Json.toJson(apps)
}
}
case class MyModel(id: Option[Int], foo: String, bar: String)
object MyModel extends Jsonable{
implicit val reader: Reads[MyModel] = new Reads[MyModel] {
def reads(json: JsValue): JsResult[MyModel] = {
for {
foo <- (json \ "foo").validate[String]
bar <- (json \ "bar").validate[String]
} yield MyModel(None, foo, bar)
}
}
// ...
}