代码之家  ›  专栏  ›  技术社区  ›  ps0604

当字段未填充时,Play Json抛出异常

  •  0
  • ps0604  · 技术社区  · 9 年前

    我有以下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 回复  |  直到 9 年前
        1
  •  2
  •   Ali Dehghani    9 年前

    使用 readNullable 相反例如,如果 act Optional :

    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], ...)