【问题标题】:Need help decoding following json with Circe需要帮助使用 Circe 解码以下 json
【发布时间】:2019-05-03 13:27:49
【问题描述】:

我正在尝试使用 Circe 库解析嵌套的 JSON 对象。我想将其映射到忽略某些字段的平面案例类。

import io.circe.generic.auto._
import io.circe.{Decoder, Encoder, HCursor, Json}

val jsonString = """{
  "parent" : {
    "name" : "title",
    "items" : [
      {
        "foo" : "",
        "attrs" : {
          "attrA" : "",
          "attrB" : ""
        }
      },
      {
        "foo" : "",
        "attrs" : {
          "attrA" : "",
          "attrB" : "",
          "attrC" : ""
        }
      }]
    }
}"""


// Notice I don't care about "attrC"
case class Item(foo: String, attrA: String, attrB: String)
case class Parent(name: String, items: List[Item])

implicit val testDecoder: Decoder[Item] = Decoder.instance { c =>
    val itemsC = c.downField("parent").downField("items")

    for {
      foo <- itemsC.get[String]("foo")
      a <- itemsC.downField("attrs").get[String]("attrA")
      b <- itemsC.downField("attrs").get[String]("attrB")
    } yield Item(foo, a, b)
  }

val decodingResult = parser.decode[Parent](jsonString)

结果: Either[io.circe.Error,Parent] = Left(DecodingFailure(Attempt to decode value on failed cursor, List(DownField(name))))

【问题讨论】:

  • 你已经尝试过什么?代码?

标签: scala circe http4s-circe


【解决方案1】:

我发现使用自动解析器更容易,将数据获取到 Scala,然后从那里继续

import io.circe.generic.auto._
import io.circe.parser._

val sample="""{
  "parent" : {
    "name" : "title",
    "items" : [
      {
        "foo" : "",
        "attrs" : {
          "attrA" : "",
          "attrB" : ""
        }
      },
      {
        "foo" : "",
        "attrs" : {
          "attrA" : "",
          "attrB" : "",
          "attrC" : ""
        }
      }
      ]
    }
  }"""


case class Data(parent : Parent)
case class Parent(name: String, items: List[Item])
case class Item(foo: String, attrs : Attrs)
case class Attrs(attrA: String, attrB: String) // you don't need attributes you don't use
val data=decode[Data](sample)

【讨论】:

  • 这看起来不错,虽然我仍然想避免辅助案例类:)
  • 正如我所说,一旦你在 Scala 中拥有它,就很容易转换成任何东西(比编写自定义解码器恕我直言更容易)
  • 我听说很多人在自动解析器中遇到边缘情况或错误。我坚持的一个问题是在我的 json 中有 scala 保留关键字,例如属性“类型”。有没有人有更让人联想到 OP 的解决方案?
  • @gutscdav000 您可能应该将此作为问题发布-而不是对 2018 年的答案发表评论..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多