无法理解为什么 validateOpt 会 return `None` 而不是 `JsError`
unable to understand why validateOpt will return `None` instead of `JsError`
在下面的代码中,我无法理解为什么 validateOpt
可能 return 值 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
...)
}
}
validateOpt
通过设计认为成功不仅是当 body
提供实际 Person
时,而且当 Person
是 null
或未提供时。请注意 documentation 如何解释返回 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
必须 always 被视为成功,因此在这种情况下应使用 validate
而不是 validateOpt
.
在下面的代码中,我无法理解为什么 validateOpt
可能 return 值 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
...)
}
}
validateOpt
通过设计认为成功不仅是当 body
提供实际 Person
时,而且当 Person
是 null
或未提供时。请注意 documentation 如何解释返回 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
必须 always 被视为成功,因此在这种情况下应使用 validate
而不是 validateOpt
.