我有一个JSON响应如下
{
......,
"phoneNumbers":[
{
"info":[
],
"phoneNumber":"1234567890",
"phoneNumberType":"HOME_NUMBER"
},
{
"info":[
],
"phoneNumber":"9876543210",
"phoneNumberType":"WORK_NUMBER"
},
{
"info":[
],
"phoneNumber":"7418529630",
"phoneNumberType":"MOBILE_NUMBER"
}
],
.......
}
我需要提取手机号码,我试试这个
val jsonBody = Json.parse(phoneListResponse.body)
val phoneList: Seq[JsValue] = (jsonBody \\ "phoneNumbers")
val mobileNodes: Seq[JsValue] = phoneList.filter(number => {
(number \\ "phoneNumberType").head.asInstanceOf[JsString].value == "MOBILE_NUMBER"
})
(mobileNodes.head \\ "phoneNumber").head.asInstanceOf[JsString].value
但是我的mobileNodes是空的。有什么建议吗?
答案 0 :(得分:1)
如果您使用Play-json
val phoneList: Seq[String] =
((jsonBody \\ "phoneNumbers")(0).as[List[JsValue]])
.filter(x => (x \ "phoneNumberType").as[String] == "MOBILE_NUMBER")
.map(x => (x \ "phoneNumber").as[String])
REPL输出
scala> ((json \\ "phoneNumbers")(0).as[List[JsValue]]).foreach(println)
{"info":[],"phoneNumber":"1234567890","phoneNumberType":"HOME_NUMBER"}
{"info":[],"phoneNumber":"9876543210","phoneNumberType":"WORK_NUMBER"}
{"info":[],"phoneNumber":"7418529630","phoneNumberType":"MOBILE_NUMBER"}
scala> ((json \\ "phoneNumbers")(0).as[List[JsValue]]).filter(x => (x \ "phoneNumberType").as[String] == "MOBILE_NUMBER")
res31: List[play.api.libs.json.JsValue] = List({"info":[],"phoneNumber":"7418529630","phoneNumberType":"MOBILE_NUMBER"})
scala> ((json \\ "phoneNumbers")(0).as[List[JsValue]]).filter(x => (x \ "phoneNumberType").as[String] == "MOBILE_NUMBER").map(x => (x \ "phoneNumber").as[String])
res32: List[String] = List(7418529630)