- Insert on the right guide page: Play JSON 2.6 -> 2.7
See JsValue
All JsValues can pattern match easily, except JsObject
because the order of its field/value entries will count, but this not wanted because in JSON object there is no order.
import play.api.libs.json._
Json.parse(""" "toto" """) match {
case JsString(str) => s"""we have the string "$str""""
case other => s"""Hu ? I didn't expect $other..."""
}
Here, please note the trick on JsNumber
: BigDecimal
has no unapply
.
import play.api.libs.json._
Json.parse("""["toto"], 1, true]""") match {
case JsArray(Seq(JsString("toto"), JsNumber(v), JsBoolean(true))) if v == BigDecimal("1")=> true
case other => false
}
In the above code, JsBoolean(true)
could be replaced with JsTrue
.
See string parsing
See traversing a JSON structure
as
throws exception on failure
asOpt
returns Some(result) or None if failure
See as
and asOpt
validate
return a JsResult
, than can be either JsSuccess
or JsError
. You can pattern match or use usual map/flatMap/fold etc.
See validate
Complete Step1_CreatingJsons; Step 1 tests must compile and pass.
Checkout Step2 branch and go to Step2: Reads