Reputation: 91
I am using the Play Json Library to parse json in scala and I have a value that looks like this
scala> val extract = (payload \ "id")
extract: play.api.libs.json.JsValue = [8,18]
I want to convert JsValue to Array[Int].
Upvotes: 0
Views: 1939
Reputation: 4063
Well, because, you are working with parsing json - which implies that along with that you need to validate it and properly handle errors, it not so easy just convert it - Play JSON will force you to handle errors. So, answering your question there you can try something like described below:
val jsonString = "{\"id\": [1, 2, 3] }"
val payload = Json.parse(jsonString)
// This will return `JsResult` - success or failure, which need to be properly handled
println((payload \ "id").validate[Array[Int]].map(_.toList))
// This is unsafe operation and might throw exception for un-expected JSON
println((payload \ "id").validate[Array[Int]].get.toList)
which prints out for me next:
JsSuccess(List(1, 2, 3),)
List(1, 2, 3)
I added toList
just for output readability. Hope this will help you!
Upvotes: 2