@rickyChen
2017-07-12T19:24:45.000000Z
字数 2312
阅读 6117
Scala
import scala.util.parsing.json.JSON
val jsonStr = """{"username":"Ricky", "age":"21"}"""
val jsonValue = JSON.parseFull(jsonStr)
val jsonObj = jsonValue match {
case Some(map:Map[String, String]) => map
case _ => println("ERROR jsonStr")
}
val username = jsonObj.get("username")
import scala.util.parsing.json.JSON
val jsonStr = """{"username":"Ricky", "attribute":{"age":21, "weight": 60}}"""
val jsonValue = JSON.parseFull(jsonStr)
val jsonObj = jsonValue match {
case Some(map:Map[String, Any]) => map
case other => println("Error jsonStr")
}
// 将attribute转换成Map
val attrObj = jsonObj.get("attribute").get.asInstanceOf[Map[String, String]]
val age = attrObj.get("age")
spary-json定义了以下数据类型, 可以根据JSON字符串定义格式
JsValue
import spray.json._
import DefaultJsonProtocol._
val jsonStr = """{"username":"Ricky", "age":"21"}"""
val jsonObj = jsonStr.parseJson.convertTo[Map[String, String]]
val username = jsonObj.get("username")
import spary.json._
import DefaultJsonProtocol._
val jsonStr = """{"username":"Ricky", "attribute":{"age":21, "weight": 60}}"""
// 这里的JsValue相当于Scala中的Any
// 当JSON字符串格式不一定是可以用这种方法
val jsonObj = jsonStr.parseJson.convertTo[Map[String, JsValue]]
val attrObj = jsonObj.get("attribute").get.asJsObject().
convertTo[Map[String,String]]
val username = jsonObj.getOrElse("username", "RickyHuo").toString
println(username)
// "username"
// 这里需要注意, JsValue中字符串自带双引号, 之后使用需要手动去除
case class Person(username: String, age:Int)
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val personFormat = jsonFormat2(Person)
}
import MyJsonProtocol._
import spray.json._
val jsonStr = """{"username":"Ricky", "age":21}"""
val jsonObj = jsonStr.parseJson.convertTo[Person]
val username = jsonObj.username
case class Person(username: String, attribute:Attribute)
case class Attribute(age: Int, weight: Int)
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val personFormat = jsonFormat2(Person)
}
import MyJsonProtocol._
import spray.json._
val jsonStr = """{"username":"Ricky", "attribute": {"age":12, "weight":60}}"""
val jsonObj = jsonStr.parseJson.convertTo[Person]
val username = jsonObj.username