1

我有以下失败(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
4

1 回答 1

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)
于 2017-09-08T14:25:31.060 回答