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

When compiling, I am getting this error message.

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

I reckon it's because box and container has each other as fields. How can i solve this problem?

1

1 Answers

0
votes

solved

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