这是我的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 _)
将其作为字符串列表解析的最佳方法是什么?
如果您希望根据评论作为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]
您可以查看此链接。
您可以使用Scala JSON解析器将JSON字符串转换为Map[String,Any]
,然后使用key
获取value
。
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.")
}