1

このJsonの一部をデコードしようとしています:

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

ただし、セット部分に到達すると失敗します。エラー メッセージは役に立ちません。

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

これが私のドコーダーです:

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

1 に答える 1

1

エラーの説明は説明的ではありませんが、問題はデコーダーのモナド API の間違った使用法に関連しています

から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)
  )
于 2017-01-10T10:58:08.563 に答える