首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要帮助用Circe解码json之后

需要帮助用Circe解码json之后
EN

Stack Overflow用户
提问于 2018-12-01 18:10:28
回答 1查看 4K关注 0票数 1

我试图用Circe库解析嵌套的JSON对象。我想把它映射到平面case类,忽略其中的一些字段。

代码语言:javascript
复制
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))))

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-01 20:34:53

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

代码语言:javascript
复制
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)
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53573659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档