首先要导入一些json4s的库,不然会报错
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._
val json = ("name" -> "zhangxing") ~ ("age" -> 35)
println(json.obj.toMap.get("age"))
implicit val formats = DefaultFormats
val g = ("topicName" -> "joe") ~ ("regularName" -> "fred")
val h = compact(render(g))
val json = parse(h)
val par = json.extract[ParseRegulation]
println(par.topicName+" /****/ "+par.regularName)
var map = Map("esc" -> "fred", "beidou" -> "zhangxing")
val realRule = new ActualRule(map)
realRule.getAllRules.foreach(println(_))
上面是一些小例子,怎么使用json4s拼接json,怎么把拼好的json转成类等等。下面要讲怎么拼接嵌套的json:
class ActualRule(regulationJson:Map[String,List[(String,String)]]) extends RuleCenter{
override def getAllRules = {
implicit val formats = DefaultFormats
regulationJson.flatMap{case (topicName,regulars) => {
regulars.map{case (regularName,attributes) =>{
("topicName" -> topicName) ~ ("regularName" -> regularName) ~ ("attributes" -> getArributes(attributes).map{
attr => (("name" -> attr.name) ~ ("ptype" -> attr.ptype) ~ ("regx" -> attr.regx) ~ ("statistics" -> attr.statistics))
})
}}
}}.map(s => s.extract[ParseRegulation])
//
}
def getArributes(attributes:String):List[Attribute] = {
attributes.split(";").map(s => s.split(",") match {
case Array(name,ptype,regx,statistics) => Attribute(name,ptype,regx,statistics)
}).toList
}
}
注意在attributes这个key上做了一层嵌套,写法如上面所示,不过有一点要注意,嵌套的类型必须是List,不然用其他的Iterator会报错。