简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM