如何在Play 2.4(Scala)中仅选择现有的JSON分支?

时间:2016-01-16 13:19:20

标签: json scala playframework playframework-2.4

编辑问题(简化)

我通过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。这可能吗?

0 个答案:

没有答案