0

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.

5
  • What is the structure of Parent and Child? Also what do you mean by "can't get it to work"? What is the error? Commented Mar 20, 2015 at 19:25
  • I've clarified the question as you've asked. The classes aren't interesting at all. I just haven't figured out how to write the writes function for Writes[Parent] correctly without using combinators. Commented Mar 20, 2015 at 20:33
  • 1
    Try wrapping parent.child with this: Json.toJson(parent.child) Commented Mar 20, 2015 at 22:06
  • Might be helpful: playframework.com/documentation/2.0/ScalaJson See: converting a Scala value the Json Commented Mar 20, 2015 at 22:11
  • 1
    It works for me without an empty Child class. Commented Mar 21, 2015 at 0:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this worked for me as well. It seems that IntelliJ is simply complaining to me about a JsValueWrapper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.