简体   繁体   中英

Play Framework: How to convert JSON to List[Int]

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM