【问题标题】:Writing complex/nested JSON Writes in Scala PlayFramework在 Scala PlayFramework 中编写复杂/嵌套的 JSON 写入
【发布时间】:2015-03-22 05:00:47
【问题描述】:

假设我有两个案例类:ChildParent,看起来像:

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

假设我已经实现了Writes[Child]。我想实现Writes[Parent]

我可以使用组合符来做到这一点:

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

但是使用以下方法,编译器会抱怨它看到类型 Child 而期待 JsValueWrapper

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

希望有人可以帮助我了解如何在不使用组合器的情况下实现 Writes[Parent]

【问题讨论】:

  • ParentChild的结构是什么?另外,您所说的“无法正常工作”是什么意思?错误是什么?
  • 我已经按照您的要求澄清了这个问题。课程一点也不有趣。我只是还没弄清楚如何在不使用组合器的情况下正确地为Writes[Parent] 编写writes 函数。
  • 尝试用这个包裹parent.childJson.toJson(parent.child)
  • 可能会有所帮助:playframework.com/documentation/2.0/ScalaJson 请参阅:将 Scala 值转换为 Json
  • 它适用于我没有空的Child 类。

标签: scala playframework playframework-json


【解决方案1】:

这确实对我有用,没有任何编译问题。

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)
}

如果您仍然遇到问题,如果您可以与 stacktrace 共享您的完整示例,将会很有用。

【讨论】:

  • 是的,这也对我有用。看来 IntelliJ 只是在向我抱怨 JsValueWrapper。
猜你喜欢
  • 2016-07-19
  • 1970-01-01
  • 2014-07-20
  • 2021-04-23
  • 1970-01-01
  • 2015-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多