未填充字段时播放 Json 抛出异常
Play Json throws exception when field is not populated
我有以下读取对象:
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 _)
问题是当这些字段之一不是来自浏览器时,我会得到一个异常并且程序失败。理想情况下,不存在的字段将可用但未定义。如何实现?
改用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], ...)
我有以下读取对象:
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 _)
问题是当这些字段之一不是来自浏览器时,我会得到一个异常并且程序失败。理想情况下,不存在的字段将可用但未定义。如何实现?
改用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], ...)