spray-json反序列化问题

时间:2017-07-03 14:49:15

标签: scala akka spray spray-json

case class Box(id: String, container: Container)
  case class Container(id: String, boxes: List[Box])

  object CustomProtocol extends DefaultJsonProtocol {
    implicit object BoxFormat extends RootJsonFormat[Box] {
      override def read(json: JsValue): Box = json.asJsObject.getFields("id", "container") match {
        case Seq(JsString(id), container) => Box(id, container.convertTo[Container])
      }
      override def write(obj: Box): JsValue = ???
    }
    implicit object ContainerFormar extends RootJsonFormat[Container] {
      override def read(json: JsValue): Container = json.asJsObject.getFields("id", "boxes") match {
        case Seq(JsString(id), boxes) => Container(id, boxes.convertTo[List[Box]])
      }
      override def write(obj: Container): JsValue = ???
    }
  }

编译时,我收到此错误消息。

Cannot find JsonReader or JsonFormat type class for app.Main.Container
    [error]         case Seq(JsString(id), container) => Box(id, container.convertTo[Container])
    [error]                                                                         ^
    [error] one error found
    [error] (compile:compileIncremental) Compilation failed

我认为这是因为盒子和容器彼此相互作为字段。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

解决

case class Box(id: String, container: Container)
  case class Container(id: String, boxes: List[Box])

  object CustomProtocol extends DefaultJsonProtocol {
    implicit object BoxFormat extends JsonFormat[Box] {
      override def read(json: JsValue): Box = json.asJsObject.getFields("id", "container") match {
        case Seq(JsString(id), container) => Box(id, container.convertTo[Container](ContainerFormat))
      }
      override def write(obj: Box): JsValue = ???
    }

    implicit object ContainerFormat extends JsonFormat[Container] {
      override def read(json: JsValue): Container = json.asJsObject.getFields("id", "boxes") match {
        case Seq(JsString(id), boxes) => Container(id, boxes.convertTo[List[Box]](listFormat(BoxFormat)))
      }
      override def write(obj: Container): JsValue = ???
    }
  }