假设我有这样的 json

{
  "sha": "some sha",
  "parents": [{
    "url": "some url",
    "sha": "some parent sha"
  }]
}

和这样的案例类
case class Commit(sha: String, parentShas: List[String])

在 play-json 中,我可以这样写:
val commitReads: Reads[Commit] = (
  (JsPath \ "sha").read[String] and
  (JsPath \ "parents" \\ "sha").read[List[String]]
)(Commit.apply _)

我正在寻找一种等效的方法来仅解码 argonaut/circe 中“parent”的“sha”,但我没有找到。 “HCursor/ACursor”有 downArray 但从那时起我不知道该怎么做。非常感谢您提前!

最佳答案

circe 和 Argonaut 都不会跟踪在 JSON 对象中读取了哪些字段,因此您可以忽略额外的 "url" 字段(就像在 Play 中一样)。更棘手的部分是找到 Play 的 \\ 等价物,circe 目前没有,尽管你已经说服我我们需要添加它。

首先,如果您有单独的 SHA 类型,这相对容易:

import io.circe.Decoder

val doc = """
{
  "sha": "some sha",
  "parents": [{
    "url": "some url",
    "sha": "some parent sha"
  }]
}
"""

case class Sha(value: String)

object Sha {
  implicit val decodeSha: Decoder[Sha] = Decoder.instance(_.get[String]("sha")).map(Sha(_))
}

case class Commit(sha: Sha, parentShas: List[Sha])

object Commit {
  implicit val decodeCommit: Decoder[Commit] = for {
    sha <- Decoder[Sha]
    parents <- Decoder.instance(_.get[List[Sha]]("parents"))
  } yield Commit(sha, parents)
}

或者,使用 Cats 的应用语法:
import cats.syntax.cartesian._

implicit val decodeCommit: Decoder[Commit] =
  (Decoder[Sha] |@| Decoder.instance(_.get[List[Sha]]("parents"))).map(Commit(_, _))

然后:
scala> import io.circe.jawn._
import io.circe.jawn._

scala> decode[Commit](doc)
res0: cats.data.Xor[io.circe.Error,Commit] = Right(Commit(Sha(some sha),List(Sha(some parent sha))))

但这并不是真正的答案,因为我不会要求您更改模型。 :) 实际答案有点不那么有趣:
case class Commit(sha: String, parentShas: List[String])

object Commit {
  val extractSha: Decoder[String] = Decoder.instance(_.get[String]("sha"))

  implicit val decodeCommit: Decoder[Commit] = for {
    sha <- extractSha
    parents <- Decoder.instance(c =>
      c.get("parents")(Decoder.decodeCanBuildFrom[String, List](extractSha, implicitly))
    )
  } yield Commit(sha, parents)
}

这很糟糕,我很惭愧这是必要的,但它有效。我刚刚提交了 an issue 以确保这在 future 的 circe 版本中变得更好。

关于json - 使用 argonaut/circe 解码 json 数组中的单个对象字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36495332/

10-11 22:28
查看更多