Circe 从 JSON 中提取列表
Circe Extract List from JSON
我有以下,但失败了(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
首先,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)
我有以下,但失败了(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
首先,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)