【问题标题】:Circe Extract List from JSONCirce 从 JSON 中提取列表
【发布时间】:2017-09-08 22:25:31
【问题描述】:

我有以下失败(0 不等于 3),我不知道为什么。有什么想法吗?

class Temp extends MyCirceExtendingClass {
  def temp(json: Json) = {
    root.otherNames.each.otherName.string.getAll(json)
  }
}

val json = Json.fromString(
  s"""
     |{
     |    id: 1,
     |    name: "Robert",
     |    isEmployee: false,
     |    otherNames: [
     |        {
     |            id: 1,
     |            otherName: "Rob"
     |        },
     |        {
     |            id: 2,
     |            otherName: "Bob"
     |        },
     |        {
     |            id: 3,
     |            otherName: "Robby"
     |        }
     |
     |    ]
     |}
     """.stripMargin)

val response = new Temp().temp(json)
response.size shouldEqual 3

【问题讨论】:

    标签: scala circe


    【解决方案1】:

    首先,Json.fromString 不解析参数,仅将其包装成 Json。其次,您的 Json 字符串格式错误:字段名称必须用引号引起来。修复这些问题后,您的镜头会给出正确的结果:

    import cats.implicits._
    import io.circe.optics.JsonPath.root
    import io.circe.parser.parse
    import io.circe.Json
    
    val json = parse(
      s"""
         |{
         |    "id": 1,
         |    "name": "Robert",
         |    "isEmployee": false,
         |    "otherNames": [
         |        {
         |            "id": 1,
         |            "otherName": "Rob"
         |        },
         |        {
         |            "id": 2,
         |            "otherName": "Bob"
         |        },
         |        {
         |            "id": 3,
         |            "otherName": "Robby"
         |        }
         |
         |    ]
         |}
     """.stripMargin).getOrElse(Json.Null)
    
    root.otherNames.each.otherName.string.getAll(json)
    
    res1: List[String] = List(Rob, Bob, Robby)
    

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 2023-03-16
      • 2019-09-15
      • 2019-07-03
      相关资源
      最近更新 更多