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)

2 years ago

解决了

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 = ???
    }
  }