使用scala lift的有效方法是什么?

时间:2013-12-18 10:48:16

标签: json scala lift lift-json

我想利用scala lift将数据从一个json合并到另一个json。在下面的示例中,在“jsonGroups”中,我想计算所有组“tom”和“dan”是其中的一部分,并将grpCount插入“jsonNames”。 println(newJson)需要等于finalOutput。 有效的方法是什么?我知道这可以减少到更少的代码行

val jsonNames = """
{
    "id" : "1B23423B",
    "payload" : {
        "list" : [ {
                "age" : "30",
                "name" : "tom",
            }, {
                "age" : "35",
                "name" : "dan"
            }]
    }
}
"""

val jsonGroups = """
{
    "id" : "1B23423B",
    "payload" : {
        "list" : [ {
                "group" : "baseball",
                "name" : "tom",
            }, {
                "group" : "basketball",
                "name" : "tom"
            }, {
                "group" : "football",
                "name" : "dan"
            }, {
                "group" : "hockey",
                "name" : "dan"
            }, {
                "group" : "football",
                "name" : "dan"
            }]
    }
}
"""

val finalOutput = """
{
    "id" : "1B23423B",
    "payload" : {
        "list" : [ {
                "age" : "30",
                "name" : "tom",
            "groupCnt" : 2
            }, {
                "age" : "35",
                "name" : "dan",
            "groupCnt" : 3
         }]
    }
}
"""

val jsGroups = parse(jsonGroups)
val groupList = jsGroups \ "payload" \ "list"
val groupMap = new HashMap[String, Int]
groupList.children.foreach { g =>
  val group = (g \ "group").values.toString
  val name = (g \ "name").values.toString
  Option(groupMap.get(name)) match {
    case Some(x) =>
      groupMap.put(name, x + 1)
    case None =>
      groupMap.put(name, 1)
  }
}

val jsNames = parse(jsonNames)   
val newJson = jsNames.transform({
  case dataObject @ JObject(fields) if fields.contains(JField("name", JString(name)))) =>
    val groupCnt = groupMap.get(name)
    dataObject.merge(("groupCnt" -> groupCnt))
})

println (pretty(render(newJson)))

1 个答案:

答案 0 :(得分:0)

可能有很多方法可以做到这一点。我个人使用的是案例类。所以,

case class JsonGroup(id: String, payload: Payload)
case class Payload(list: List[PayloadList])
case class PayloadList(group: String, name: String)
val groups: Option[JsonGroup] = jsonGroups.extractOpt[JsonGroup]

groups.foreach(group => println(group.payload.list(2).name)

之后你应该做自定义逻辑。