【问题标题】:Read JSON in Scala whose key/value pairs and types are unknown在 Scala 中读取其键/值对和类型未知的 JSON
【发布时间】:2018-05-03 06:21:18
【问题描述】:

我如何遍历JSON 对象without knowing key/value pairs 及其在Scala 中的类型

【问题讨论】:

    标签: json scala


    【解决方案1】:

    您可以使用常规遍历方法,例如

    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.htmlhttps://circe.github.io/circe/api/io/circe/Json.htmlhttps://github.com/circe/circe/blob/master/modules/core/shared/src/main/scala/io/circe/Json.scala#L95-L100

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 2016-06-29
      • 2017-08-02
      • 1970-01-01
      • 2021-02-19
      相关资源
      最近更新 更多