scala json4s我怎么能按条件提取字段

时间:2016-07-15 09:28:20

标签: json scala json4s

我有json(例如):

{
  "name": "",
  "count": 2,
  "children": {
    "app_open": {
      "name": "app_open",
      "count": 1,
      "children": {
        "session_end": {
          "name": "session_end",
          "count": 1,
          "children": {}
        }
      }
    },
    "app_install": {
      "name": "app_install",
      "count": 2,
      "children": {
        "session_end": {
          "name": "session_end",
          "count": 2,
          "children": {}
        }
      }
    },
    "app_instal1l": {
      "name": "app_instal1l",
      "count": 3,
      "children": {
        "app_open": {
          "name": "app_open",
          "count": 3,
          "children": {
            "session_end": {
              "name": "session_end",
              "count": 3,
              "children": {}
            }
          }
        }
      }
    }
  }
}

我需要提取“name”=“app_open”的所有计数。

我尝试使用json4s库:

val name = jsonInput filterField {
           case JField("name", "app_open") => true
           case _ => false
         }
println("name = " + URL)

我建议输出中我只有“app_open”,但我得到了:

name = List((name,JString(app_open)), (name,JString(session_end)), 
(name,JString(app_open)), (name,JString(session_end)))

我在这里做错了什么? 谢谢!

1 个答案:

答案 0 :(得分:2)

编译错误很明显:

Error: type mismatch;
 found   : String("app_open")
 required: org.json4s.JsonAST.JValue
    case JField("name", "app_open") => true
                    ^

那是因为type JField = (String, JValue)。请使用JValue代替String

val name = jsonInput filterField {
  case JField("name", JString("app_open")) => true
  case _ => false
}