如何用play json库解析二级JSON数组?

时间:2018-02-23 11:16:35

标签: json scala parsing playframework

这是我的Json:

{
  "root": {
    "qr": {
      "content": "V1"
    },
    "datag": {
      "content": {

        "business": {
          "content": [
            {
              "content": "car"
            },
            {
              "content": "bike"
            }
          ]
        }

      }
    }
  }
}

这是我的尝试但收到编译错误:

implicit val reads: Reads[rules] = (
   (JsPath \ "content" \ "qr" \ "content").readNullable[String] and
    (JsPath \ "content" \ "datag" \ "content" \ "business" \ "content").readNullable[Seq[String]]
 )(rules.apply _)   

将其解析为字符串列表的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

如果您希望根据评论将答案设为List("car","bike"),并且您正在寻找一个班轮,那么您可以试试这个

val json = Json.parse("""{
 |   "root": {
 |     "qr": {
 |       "content": "V1"
 |     },
 |     "datag": {
 |       "content": {
 | 
 |         "business": {
 |           "content": [
 |             {
 |               "content": "car"
 |             },
 |             {
 |               "content": "bike"
 |             }
 |           ]
 |         }
 | 
 |       }
 |     }
 |   }
 | }""")

val contents = (json \ "root" \ "datag" \ "content" \ "business" \ "content" ).as[List[Map[String, String]]].flatMap(_.values)
//this can throw an error if the data under 'content' is not a List
val contentsNew = (json \ "root" \ "datag" \ "content" \ "business" \ "content" ).asOpt[List[Map[String, String]]].map(_.flatMap(_.values)).fold(List.empty[String])(identity)
//this one is safe option 

或者我建议创建一个案例类,然后使用Json.format[CaseClass],你可以看看这个link

答案 1 :(得分:0)

您可以使用scala json解析器将json字符串转换为Map[String,Any],然后使用value获取key

import scala.util.parsing.json._
val jsonString =
    """{
      |  "root": {
      |    "qr": {
      |      "content": "V1"
      |    },
      |    "datag": {
      |      "content": {
      |
      |        "business": {
      |          "content": [
      |            {
      |              "content": "car"
      |            },
      |            {
      |              "content": "bike"
      |            }
      |          ]
      |        }
      |
      |      }
      |    }
      |  }
      |}""".stripMargin

函数迭代复杂的json以获取键列表并获取内部json值。

def getValue(input: Map[String, Any], keys: List[String]): Any = keys match {
    case lastKey :: Nil => input(lastKey)
    case key :: _ => getValue(input(key).asInstanceOf[JSONObject].obj, keys.tail)
  }

最后解析json并得到输出:

JSON.parseRaw(jsonString) match {
    case Some(jsonVal) =>
      println(jsonVal)
      val jsonMapKeyValuePair: Map[String, Any] =
        jsonVal.asInstanceOf[JSONObject].obj
      val keys = List("root", "datag", "content", "business", "content")
      val output: List[Any] =
        getValue(jsonMapKeyValuePair, keys)
          .asInstanceOf[JSONArray]
          .list
          .map(_.asInstanceOf[JSONObject].obj)
          .map(_.get("content").get)
      println(output)
    case _ =>
      println("Invalid Json Object.")
  }