我通过REST API获取输入JSON对象,并希望将其转换为新的经过验证的JSON对象。所有属性/分支都是可选的。
到目前为止,我的Play 2.4动作:
import play.api.mvc._
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
// [...]
def updateUser(id: String) = Action(parse.json) { request =>
/** Name validaton */
val nameReads: Reads[JsString] = Reads.of[JsString] keepAnd
Reads.minLength[String](2) keepAnd
Reads.maxLength[String](20) keepAnd
Reads.pattern("""[a-z]*""".r)
/** Age validaton */
val ageReads: Reads[JsNumber] = Reads.of[JsNumber] keepAnd
Reads.min(18) keepAnd
Reads.max(128)
/** Transformer */
val transformUser: Reads[JsObject] = (
(__ \ 'name).json.pickBranch(nameReads) and
(__ \ 'age).json.pickBranch(ageReads)
).reduce
// I guess I'd like to have something like this:
// val transformUser: Reads[JsObject] = (
// (__ \ 'name).json.pickBranchIfExists(nameReads) and
// (__ \ 'age).json.pickBranchIfExists(ageReads)
// ).reduce
val inputJson: JsValue = request.body
inputJson.transform(transformUser).map { resultJsObj =>
Ok(resultJsObj)
} recoverTotal { err =>
val errJsObj: JsObject = JsError.toJson(err)
BadRequest(errJsObj)
}
}
现在我正在寻找既不是pickBranch
也不是prune
的东西,更像是pickBranchIfExsists
。这可能吗?