Reputation: 9724
Given the following JSON string...
val jsonStr = "[1, 2, 3]"
... how do I convert it into a List[Int]
? The following statement returns a JsValue
, which does not contain method read
:
Json.parse(jsonStr)
Upvotes: 2
Views: 3449
Reputation: 139038
Play provides several ways to decode JSON. The "simplest" is as
:
scala> import play.api.libs.json._
import play.api.libs.json._
scala> val jsonStr = "[1, 2, 3]"
jsonStr: String = [1, 2, 3]
scala> val json = Json.parse(jsonStr)
json: play.api.libs.json.JsValue = [1,2,3]
scala> val xs = json.as[List[Int]]
xs: List[Int] = List(1, 2, 3)
This will throw an exception in the case that you don't actually have a list of integers, though, so it's generally a bad idea. asOpt
and validate
are much better:
scala> val xsMaybe = json.asOpt[List[Int]]
xsMaybe: Option[List[Int]] = Some(List(1, 2, 3))
scala> val xsResult = json.validate[List[Int]]
xsResult: play.api.libs.json.JsResult[List[Int]] = JsSuccess(List(1, 2, 3),)
Now you're forced by the type system to deal with the possibility of error, which means fewer surprises at runtime.
All of these methods take an implicit Reads[_]
argument. Play provides instances for Reads[Int]
and Reads[List[A: Reads]]
out of the box, and you can get the same syntax for your own types by defining your own Reads
instances.
Upvotes: 5