5

I'm trying to come up with a nice approach to building my json for some api calls I want to do from my Play application to some other service.

I'm running into an issue when trying to create an abstract class that I want to include in my case classes. I have a general Request object and want to include Parameter objects in that, Login is an example of a Parameters object, but the contents can vary.

I tried creating a companion object, working with a trait instead of abstract class and tried to implement manual Writer objects instead of using the "inception" method, however I can't get the type system to do what I want and the documentation doesn't describe what I'm trying to do.

package sandbox

import play.api.libs.json._
import play.api.libs.functional.syntax._

object JsonTest {
    abstract class Parameters

    case class Request(
        interface: String,
        method: String,
        parameters: Parameters
    )

    case class Login(username: String, password: String) extends Parameters

    implicit val loginWrites = Json.writes[Login]
    implicit val requestWrites = Json.writes[Request]

    val login = Login("user1", "pass1")
    val request = Request("interface1", "method1", login)
    val requestJS = Json.toJson(request)
}

The above snippet correctly complains that it doesn't have a writer for Parameters, what would be the cleanest approach to making something like this work?

mvaerle
  • 51
  • 2
  • 1
    You could make your `Parameters` class `sealed` and create `Writes[Parameters]`. See [this answer](http://stackoverflow.com/a/21036340/406435). – senia Jan 12 '14 at 12:53
  • Thanks for pointing to that post, I wasn't sure if that would fix my case. It seems to work, although there is a lot more boilerplate involved and I have to repeat all the subclasses in the Writes[Parameters] block – mvaerle Jan 12 '14 at 19:54
  • At least you can't miss subclass in `Writes[Parameters]`. – senia Jan 12 '14 at 20:40
  • possible duplicate of [Creating Read\[T\] and Write\[T\] for Abstract Class](http://stackoverflow.com/questions/21718075/creating-readt-and-writet-for-abstract-class) – johanandren Dec 12 '14 at 12:15

0 Answers0