【问题标题】:use Scala to get JSON data in lower levels使用 Scala 获取较低级别的 JSON 数据
【发布时间】:2015-07-04 22:23:01
【问题描述】:

我是 Scala 的初学者,我的 JSON 数据格式如下:

{
    "index_key": {
        "time":"12938473",
        "event_detail": {
            "event_name":"click",
            "location":"US"
        }
    }
}

我正在尝试获取“index_key”的内容并将二级内容提取为新的 JSON 对象并根据二级数据启动一个类。

{
    "time":"12938473",
    "event_detail": {
        "event_name":"click",
        "location":"US"
    }
}

我尝试使用json4s从上面的json中提取出一个Event类,但是如何去掉第一级key的“index_key”呢?

 case class Detail(event_name: String, location: String)
 case class Event(time: String, event_detail: Detail)

 json.extract[Event]

我已经阅读了 json4s 文档,还阅读了 http://www.scala-lang.org/api/2.10.3/index.html#scala.util.parsing.json.JSON$,但还是不太明白,因为预定义的 json 似乎应该适合解析器?

谁能告诉我如何获取 json 结构的二级数据(或任何更低级别)?

【问题讨论】:

  • 不推荐使用此 JSON API 以使用专用且最新的 JSON 库。
  • 为什么不case class Wrapper(index_key: Event)
  • 哦...你是对的...我绝对可以使用 wapper 类,非常感谢 Rex。但我只想知道如果我只想解析出 json 字符串的内部内容怎么办? @RexKerr
  • 我将使用 json4s,感谢@cchantep 的提醒

标签: java arrays json scala json4s


【解决方案1】:

您可以使用\ 来获取您要提取的对象:

val json = parse(str) \ "index_key"
json.extract[Event]

【讨论】:

  • 嗨@bjfletcher,只是另一个快速的scala问题,如何将“index_key”作为变量?我正在尝试使其成为通用 json 格式并解析所有内部内容,但“index_key”可能是其他名称,如“index_key2”、“index_key3”。非常感谢:P
  • parse(str).as[JsObject].values.head :)
  • ":26: error: not found: type JsObject" and "error: No JSON deserializer found for type . 尝试为此类型实现隐式 Reader 或 JsonFormat。"在 parse(str).as[JsObject].
  • 我google了一下,发现应该安装“播放框架”?我现在只在控制台模式下使用 json4s。非常感谢
  • 抱歉,一些 Play JSON 问题飞来飞去,我忘记了这是 json4s! :) json4s 版本:parse(str).as[JObject].children.head
猜你喜欢
  • 2020-02-01
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
相关资源
最近更新 更多