[关闭]
@rickyChen 2017-07-12T19:24:45.000000Z 字数 2312 阅读 6117

Scala如何处理(多级)JSON字符串

Scala


1.JSON.parseFull

  1. import scala.util.parsing.json.JSON
  2. val jsonStr = """{"username":"Ricky", "age":"21"}"""
  3. val jsonValue = JSON.parseFull(jsonStr)
  4. val jsonObj = jsonValue match {
  5. case Some(map:Map[String, String]) => map
  6. case _ => println("ERROR jsonStr")
  7. }
  8. val username = jsonObj.get("username")
  1. import scala.util.parsing.json.JSON
  2. val jsonStr = """{"username":"Ricky", "attribute":{"age":21, "weight": 60}}"""
  3. val jsonValue = JSON.parseFull(jsonStr)
  4. val jsonObj = jsonValue match {
  5. case Some(map:Map[String, Any]) => map
  6. case other => println("Error jsonStr")
  7. }
  8. // 将attribute转换成Map
  9. val attrObj = jsonObj.get("attribute").get.asInstanceOf[Map[String, String]]
  10. val age = attrObj.get("age")

2.spary-json

DefaultJsonProtocol

spary-json定义了以下数据类型, 可以根据JSON字符串定义格式

  1. import spary.json._
  2. import DefaultJsonProtocol._
  3. val jsonStr = """{"username":"Ricky", "attribute":{"age":21, "weight": 60}}"""
  4. // 这里的JsValue相当于Scala中的Any
  5. // 当JSON字符串格式不一定是可以用这种方法
  6. val jsonObj = jsonStr.parseJson.convertTo[Map[String, JsValue]]
  7. val attrObj = jsonObj.get("attribute").get.asJsObject().
  8. convertTo[Map[String,String]]
  9. val username = jsonObj.getOrElse("username", "RickyHuo").toString
  10. println(username)
  11. // "username"
  12. // 这里需要注意, JsValue中字符串自带双引号, 之后使用需要手动去除

YourJsonProtocol(自定义协议)

  1. case class Person(username: String, age:Int)
  2. object MyJsonProtocol extends DefaultJsonProtocol {
  3. implicit val personFormat = jsonFormat2(Person)
  4. }
  5. import MyJsonProtocol._
  6. import spray.json._
  7. val jsonStr = """{"username":"Ricky", "age":21}"""
  8. val jsonObj = jsonStr.parseJson.convertTo[Person]
  9. val username = jsonObj.username
  1. case class Person(username: String, attribute:Attribute)
  2. case class Attribute(age: Int, weight: Int)
  3. object MyJsonProtocol extends DefaultJsonProtocol {
  4. implicit val personFormat = jsonFormat2(Person)
  5. }
  6. import MyJsonProtocol._
  7. import spray.json._
  8. val jsonStr = """{"username":"Ricky", "attribute": {"age":12, "weight":60}}"""
  9. val jsonObj = jsonStr.parseJson.convertTo[Person]
  10. val username = jsonObj.username

3.Reference

spary-json

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注