ps0604
ps0604

Reputation: 1071

Play Json throws exception when field is not populated

I have the following Reads object:

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 _)

The problem is that when one of these fields doesn't come from the browser, I get an exception and the program fails. Ideally, the non present field will be available but undefined. How to achieve that?

Upvotes: 0

Views: 109

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48133

Use readNullable instead. For example, if act is 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 _)

And of course your BranchApplyRequest would be like this:

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

Upvotes: 2

Related Questions