0

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?

1
  • 1
    What json lib are you using? That could be a number of them (I've lost count of how many json libs Scala+Java has.) Commented Sep 12, 2016 at 18:42

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Still phoneList is empty.
@αƞjiβ here is the repl output for step wise execution
@αƞjiβ I have edited the answer Please notice the (0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.