Search code examples
jsonscalaplayframeworkplay-json

Extract Json attribute value from JsArray ( play )


Following is snippet from my scala code. I am using play 2.4. Below is the ouput of my "message" val.

import play.api.libs.json._

              .map{ _ match {
                  case (Some( message :JsArray  ), x) => {
                       println(      message  )
                       println((message \\ "collectorId").map(_.as[Int]))
                   }
               }

output :

["{\"id\":1,\"createdAt\":\"2015-11-11T16:18:58.789\",\"collectorId\":4}", "{\"id\":5,\"createdAt\":\"2015-11-11T22:35:52.300\",\"collectorId\":5}", "{\"id\":2,\"createdAt\":\"2015-11-11T16:21:05.377\",\"collectorId\":4}", "{\"id\":3,\"createdAt\":\"2015-11-11T22:35:20.408\",\"collectorId\":2}", "{\"id\":4,\"createdAt\":\"2015-11-11T22:35:38.602\",\"collectorId\":4}"]

ListBuffer()

How to extract

"collectorId"

value as Seq[Int]. When I execute the code I get it as ListBuffer().

I found that JsObject should be there in place of JsArray.

Thanks for the support guys. Here is how I was able to solve the issue.

case (Some( message :JsArray ), response ) => {
       (message \\ "collectorId").map{_ match { case JsNumber(s) =>  s.intValue() }
       }
}

Solution

  • Use

    (message \\ "collectorId" map(_.as[Int]) toSeq
    //> res0: Seq[Int] = List(4, 5, 4, 2, 4)
    

    where message is JArray.