json4s 嵌套使用

首先要导入一些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会报错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值