播放Json时,如果未填充字段,则会抛出异常

时间:2016-02-16 12:36:17

标签: scala playframework playframework-2.0

我有以下Reads对象:

implicit val branchRead: Reads[BranchApplyRequest] = (
      (JsPath \ "act").read[String] and
      (JsPath \ "st").read[String] and
      (JsPath \ "nts").read[String] and
      (JsPath \ "bk").read[Int]
    ) (BranchApplyRequest.apply _)

问题是,当其中一个字段不是来自浏览器时,我会收到异常并且程序失败。理想情况下,非现场字段可用但未定义。如何实现?

1 个答案:

答案 0 :(得分:2)

请改用readNullable。例如,如果actOptional

implicit val branchRead : Reads[BranchApplyRequest] = (
      (JsPath \ "act").readNullable[String] and
      (JsPath \ "st").read[String] and
      (JsPath \ "nts").read[String] and
      (JsPath \ "bk").read[Int]
    )(BranchApplyRequest.apply _)

当然,您的BranchApplyRequest将是这样的:

case class BranchApplyRequest(act: Option[String], ...)