在下面的代码中,我无法理解为什么validateOpt
可能返回值JsSuccess(None)
而不是JsError
def getQuestion = silhouette.UserAwareAction.async{
implicit request => {
val body: AnyContent = request.body
val jsonBodyOption: Option[JsValue] = body.asJson
jsonBodyOption.map((jsonBody:JsValue) => { //body is json
val personJsonJsResultOption = jsonBody.validateOpt[Person]//check that json structure is correct
personJsonJsResultOption match {
case personSuccessOption: JsSuccess[Option[Person]] => { //json is correct
val personOption = personSuccessOption.getOrElse(None) //why would getOrElse return None??
personOption match {
case Some(person) => {
... }
case None =>{ //I am not sure when this will be triggered.
...
}
}
}
}
case e: JsError => {
...
}
}
}
})
.getOrElse(//body is not json
...)
}
}
答案 0 :(得分:0)
x
设计上认为成功不仅在于if x := isBig(y): return x
提供实际的validateOpt
,而且还在于body
为Person
或不提供时。请注意documentation如何解释返回Person
的原因:
null
似乎您的要求是必须始终{strong>始终提供JsSuccess(None)
才能被认为是成功的,因此在这种情况下,应使用 /**
* If this result contains `JsNull` or is undefined, returns `JsSuccess(None)`.
* Otherwise returns the result of validating as an `A` and wrapping the result in a `Some`.
*/
def validateOpt[A](implicit rds: Reads[A]): JsResult[Option[A]]
而不是Person
。