如何在JSON
without knowing key/value pairs
对象Scala
及其类型
答案 0 :(得分:2)
您可以使用常规遍历方法,例如
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