无法解码Circe中的Set

时间:2017-01-09 23:01:11

标签: json scala circe

我正在尝试解码这片Json:

{
  "id" : "e07cff6a-bbf7-4bc9-b2ec-ff2ea8e46288",
  "paper" : {
    "title" : "Example Title",
    "authors" : [
      "1bf5e911-8878-4e06-ba8e-8159aadb052c"
    ]
  }
}

但是,当它到达Sets部分时,它会失败。错误消息没有帮助。

DecodingFailure([A]Set[A], List())

以下是我的docoders:

  implicit val paperIdDecoder: Decoder[PaperId] = Decoder.decodeString.emap[PaperId] { str ⇒
    Either.catchNonFatal(PaperId(str)).leftMap(_.getMessage)
  }

  implicit val paperAuthorDecoder: Decoder[PaperAuthor] = Decoder.decodeString.emap[PaperAuthor] { str ⇒
    Either.catchNonFatal(PaperAuthor(str)).leftMap(_.getMessage)
  }

  implicit val paperDecoder: Decoder[Paper] = {
    for {
      title <- Decoder.decodeString
      authors <- Decoder.decodeSet[PaperAuthor]
    } yield Paper(title, authors)
  }

  implicit val paperViewDecoder: Decoder[PublishedPaperView] = for {
    id <- Decoder[PaperId]
    paper <- Decoder[Paper]
  } yield PublishedPaperView(id, paper) 

以下是使用的案例类:

case class PublishedPaperView(id: PaperId, paper: Paper)

case class PaperId(value: String) 

case class Paper(title: String, authors: Set[PaperAuthor])

case class PaperAuthor(value: String)

1 个答案:

答案 0 :(得分:1)

虽然错误描述远非解释,但您的问题与解码器的 monadic API 的错误使用有关:请记住,for comprehension是地图的语法糖/ flatMap。

来自io.circe.Decoder

  /**
   * Monadically bind a function over this [[Decoder]].
   */
  final def flatMap[B](f: A => Decoder[B]): Decoder[B] = new Decoder[B] {
    final def apply(c: HCursor): Decoder.Result[B] = self(c).flatMap(a => f(a)(c))

    override def tryDecode(c: ACursor): Decoder.Result[B] = {
      self.tryDecode(c).flatMap(a => f(a).tryDecode(c))
    }

    override def decodeAccumulating(c: HCursor): AccumulatingDecoder.Result[B] =
      self.decodeAccumulating(c).andThen(result => f(result).decodeAccumulating(c))
  }

看一下这段代码,你会看到当你对一个解码器进行flatMap时,会得到一个新的解码器,它运行在同一个游标上:光标是解析操作的当前位置。

在以下代码中:

implicit val paperDecoder: Decoder[Paper] = {
    for {
      title <- Decoder.decodeString
      authors <- Decoder.decodeSet[PaperAuthor]
    } yield Paper(title, authors)
  }

当您尝试解码标题和作者时,光标指向对象的开头。如果您不使用半自动或自动生成并且您使用API​​本机工作,那么需要像这样自己移动光标

  implicit val paperDecoder: Decoder[Paper] = Decoder.instance(cursor => Xor.right(Paper("",Set.empty)))

  implicit val paperViewDecoder: Decoder[PublishedPaperView] = Decoder.instance(
    cursor =>
      for {
        id <- cursor.downField("id").as[PaperId]
        paper <- cursor.downField("paper").as[Paper]
     } yield PublishedPaperView(id, paper)
  )