您还可以在 for comprehension 中组合多个读取/验证步骤。以下是两个函数,一个返回 an Option[_]
,一个返回 a Boolean
。第一个允许也处理数据,而后者只进行验证。
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