使用Scala Parser解析JSON

原博客地址:使用Scala Parser解析JSON

import scala.util.parsing.combinator._

class JsonParser extends JavaTokenParsers {
	def jNum: Parser[Double] = floatingPointNumber ^^ (_.toDouble)
	def jStr: Parser[String] = stringLiteral ^^ (s => s.substring(1, s.length() - 1))
	def jBool: Parser[Boolean] = "(true|false)".r ^^ (_.toBoolean)
	def jNull: Parser[Null] = "null".r ^^ (t => null)
	def term = jsonArray | jsonObject | jNum | jBool | jNull | jStr
	def jsonArray: Parser[List[Any]] = "[" ~> rep(term <~ ",?".r) <~ "]" ^^ (l => l)
	def jsonObject: Parser[Map[String, Any]] = "{" ~> rep((
		ident ~ ":" ~ jNum |
		ident ~ ":" ~ jBool |
		ident ~ ":" ~ jNull |
		ident ~ ":" ~ jsonObject |
		ident ~ ":" ~ jsonArray |
		ident ~ ":" ~ jStr) <~ ",?".r
	) <~ "}" ^^ {
		os =>
			var map = Map[String, Any]()
			os.foreach(o =>
				o match {
					case k ~ ":" ~ v => map = map ++ Map(k -> v)
				}
			)
			map
	}
}
object JsonParser_Ex extends JsonParser with App{
	val result = parseAll(jsonObject, """{a:[1,2,"a",{name:"cc"}],b:1,c:"cc",d:null,e:true}""")
	println(result)
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值