Scala中Json解析String,获得多级key

9 篇文章 0 订阅

代码块

导入包

import scala.util.parsing.json._

def main(args: Array[String]): Unit = {

    def regJson(json:Option[Any]) = json match {
      case Some(map: Map[String, Any]) => map
//      case None => "erro"
//      case other => "Unknow data structure : " + other
    }
    val str = "{\"host\":\"td_test\",\"ts\":1486979192345,\"device\":{\"tid\":\"a123456\",\"os\":\"android\",\"sdk\":\"1.0.3\"},\"time\":1501469230058}"
    val jsonS = JSON.parseFull(str)
    val first = regJson(jsonS)
    // 获取一级key
    println(first.get("host"))
    // 获取二级key
    val dev = first.get("device")
    println(dev)
    val sec = regJson(dev)
    println(sec.get("tid").toString.replace("Some(","").replace(")",""))
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

运行结果

Some(td_test) 
Some(Map(tid -> a123456, os -> android, sdk -> 1.0.3)) 
a123456

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scala 解析 JSON 可以使用多种库,其最常用的是 `Play JSON` 和 `Circe`。下面我将为你提供两种常见的解析方式。 1. 使用 Play JSON: 首先,你需要在项目的 build.sbt 文件添加以下依赖项: ```scala libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.2" ``` 然后,你可以按照以下步骤解析 JSON: ```scala import play.api.libs.json._ // 定义一个 case class 表示你的 JSON 结构 case class Person(name: String, age: Int) // 创建一个 Json Reads 实例用于解析 JSON implicit val personReads: Reads[Person] = Json.reads[Person] // 解析 JSON val jsonStr = """{"name": "John", "age": 30}""" val json = Json.parse(jsonStr) val personResult = json.validate[Person] personResult match { case JsSuccess(person, _) => println(person) // 解析成功 case JsError(errors) => println(errors) // 解析失败 } ``` 2. 使用 Circe: 首先,你需要在项目的 build.sbt 文件添加以下依赖项: ```scala libraryDependencies += "io.circe" %% "circe-core" % "0.14.1" libraryDependencies += "io.circe" %% "circe-generic" % "0.14.1" ``` 然后,你可以按照以下步骤解析 JSON: ```scala import io.circe._ import io.circe.parser._ import io.circe.generic.auto._ // 定义一个 case class 表示你的 JSON 结构 case class Person(name: String, age: Int) // 解析 JSON val jsonStr = """{"name": "John", "age": 30}""" val json = parse(jsonStr).getOrElse(Json.Null) val personResult = json.as[Person] personResult match { case Right(person) => println(person) // 解析成功 case Left(error) => println(error) // 解析失败 } ``` 以上是两种常见的解析 JSON 的方式,你可以根据自己的需求选择适合的库和方法。希望对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值