Search code examples
jsonscalaplayframeworkplayframework-2.5

Scala Play: how to define a "Json writable class"


I would like to write a function that transforms case classes to Json:

import play.api.libs.json._

def myJson(cc: Product): JsValue = {
  Json.toJson(cc)  // simplified
}

Each case class has an implicit Writes[T], for example:

case class Test(a: Int)
object Test {
  implicit val jsonWrites: Writes[Test] = Json.writes[Test]
}

It is possible to write Json.toJson(new Test(1)) individually, but the myJson function above does not compile because it never knows if cc has an implicit Writes defined.

[How can I write the function signature so that it takes only classes having a Writes implicit?]

Edit: How can I write the function input type so that it corresponds only to classes having a Writes implicit?

I tried this:

trait JsonWritableResult[T <: Product] {
  implicit val jsonWrites: Writes[T]
}

case class Test(a: Int)
object Test extends JsonWritableResult[Test] {
  implicit val jsonWrites: Writes[Test] = Json.writes[Test]
}

def myJson(cc: JsonWritableResult[_ <: Product]): JsValue = {
  Json.toJson(cc)
}

But it says "No Json serializer found for type models.JsonWritableResult[_$2]".


Solution

  • Something like this seems to give you the behavior you want.

    import play.api.libs.json.{JsValue, Json, Writes}
    
    trait Product {}
    
    case class Test(a: Int) extends Product
    object Test {
      implicit val jsonWrites: Writes[Test] = Json.writes[Test]
    }
    
    def myJson[T <: Product](cc: T)(implicit writes: Writes[T]): JsValue = {
      Json.toJson(cc)  // simplified
    }
    
    import Test._
    
    myJson(Test(3))
    

    This is not tested in the general case, but in a Worksheet it seems to work.