Search code examples
jsonplayframeworktraits

Json formatter for traits in Play 2.4


Am having a trait

  trait Role[A, B] {
    val _id: Option[A] = None
    val value: Option[List[B]] = None
    val id: Option[String] = None
  }

And the case class extending the trait

case class User (value1: Option[Role] = None, value2: Option[String] = None) extends Role

object User { 
implicit val jsonFormatter: Format[User] = Json.format[User]
}

And it is not compiling because of the error, "No Json formattor for Role".

I tried several examples available in stackoverflow, on json formatter for traits Nothing gets worked.


Solution

  • Yes, this is correct, since when Play try to do a formatting for User, it doesn't know how to format Role to json.

    You could do that, by first adding something like:

    implicit val roleFormat = Json.format[Role]
    

    to the object User

    Requirements from the Play documentation:

    These macros rely on a few assumptions about the type they’re working with :

    • It must have a companion object having apply and unapply methods
    • The return types of the unapply must match the argument types of the apply method.
    • The parameter names of the apply method must be the same as the property names desired in the JSON.

    Case classes natively meet these requirements. For more custom classes or traits, you might have to implement them.