You can also combine multiple read/validation steps inside a for comprehension. Following are two functions, one which returns an Option[_]
and one which returns a Boolean
. The first one allows to also work with the data, while the latter only does validation.
import org.json4s.jackson.JsonMethods._
val text =
"""
|{
| "foo": "bar",
| "baz": "fnord",
| "qux": true
|}
""".stripMargin
val json = parse(text)
def readFoo(x: JValue): Option[(String, String, Boolean)] = for {
JObject(_) <- x.toOption
JString(foo) <- (x \ "foo").toOption
JString(baz) <- (x \ "baz").toOption
JBool(qux) <- (x \ "qux").toOption
if (qux == true)
} yield (foo, baz, qux)
def validateOnly(x: JValue): Boolean = (for {
JObject(_) <- x.toOption
JString(foo) <- (x \ "foo").toOption
JString(baz) <- (x \ "baz").toOption
JBool(qux) <- (x \ "qux").toOption
if (qux == true)
} yield true) getOrElse false
println(readFoo(json)) // Some((bar,fnord,true))
println(readFoo(json).isDefined) // true
println(validateOnly(json)) // true