αƞjiβ αƞjiβ - 2 months ago 16
Scala Question

Reading value from JSON string Scala using ScalaJson

I have a JSON response as follow

{
......,

"phoneNumbers":[
{
"info":[

],
"phoneNumber":"1234567890",
"phoneNumberType":"HOME_NUMBER"
},
{
"info":[

],
"phoneNumber":"9876543210",
"phoneNumberType":"WORK_NUMBER"
},
{
"info":[

],
"phoneNumber":"7418529630",
"phoneNumberType":"MOBILE_NUMBER"
}
],

.......

}


I need to extract mobile number and I try like this

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


But my mobileNodes is empty. Any suggestion?

Answer

If you are using 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 output

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)
Comments