【发布时间】:2018-05-03 06:21:18
【问题描述】:
我如何遍历JSON 对象without knowing key/value pairs 及其在Scala 中的类型
【问题讨论】:
我如何遍历JSON 对象without knowing key/value pairs 及其在Scala 中的类型
【问题讨论】:
您可以使用常规遍历方法,例如
import cats.syntax.either._
import io.circe._, io.circe.parser._
val json: String = """
{
"id": "c730433b-082c-4984-9d66-855c243266f0",
"name": "Foo",
"counts": [1, 2, 3],
"values": {
"bar": true,
"baz": 100.001,
"qux": ["a", "b"]
}
}
"""
val doc: Json = parse(json).getOrElse(Json.Null)
val baz: Decoder.Result[Json] =
cursor.downField("values").downField("baz").as[Json]
解码为Json 让您在之后对其进行模式匹配。
baz.map({
case JNull => "Null"
case JBoolean(_) => "Boolean"
case JNumber(_) => "Number"
case JString(_) => "String"
case JArray(_) => "Array"
case JObject(_) => "Object"
})
来源:https://circe.github.io/circe/cursors.html、https://circe.github.io/circe/api/io/circe/Json.html、https://github.com/circe/circe/blob/master/modules/core/shared/src/main/scala/io/circe/Json.scala#L95-L100
【讨论】: