0

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?

Ali Dehghani
  • 43,096
  • 14
  • 154
  • 142
ps0604
  • 1,513
  • 20
  • 113
  • 274
  • Possible duplicate of [Play Framework 2.2.2 Scala JSON reads with undefined/null elements causing NoSuchElementException](http://stackoverflow.com/questions/22757649/play-framework-2-2-2-scala-json-reads-with-undefined-null-elements-causing-nosuc) – Zoltán Feb 16 '16 at 12:55

1 Answers1

2

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], ...)
Ali Dehghani
  • 43,096
  • 14
  • 154
  • 142