Search code examples
scalaplayframeworkplayframework-json

Writing complex/nested JSON Writes in Scala PlayFramework


Going to assume that I have two case classes: Child, Parent that look something like:

case class Child()
case class Parent(child: Child)

Assume I've already implemented Writes[Child]. I'd like to implement Writes[Parent].

I'm able to do this using combinators:

implicit val parentWrites: Writes[Parent] = (
   (__ \ "child").write[Child]
)(unlift(Parent.unapply))

But with the following approach, the compiler complains that it's seeing the type Child while expecting a JsValueWrapper:

implicit val parentWrites = new Writes[Parent] {
   def writes(parent: Parent) = Json.obj(
      "child" -> parent.child
   )
}

Hoping someone can help me understand how to implement a Writes[Parent] without using combinators.


Solution

  • This does work for me without any compile issues.

    import play.api.libs.json._
    
    case class Child(t: String)
    case class Parent(child: Child)
    
    implicit val parentWrites = new Writes[Parent] {
      def writes(parent: Parent) = Json.obj("child" -> parent.child)
    }
    

    If you are still having trouble, it would be useful if you can share your complete sample with stacktrace.