I have a:
case class Product(
id: Option[Int],
name: String,
measure: Int,
qty: Double = 0
)
and implicit json Reads
in the Controller:
implicit val productReads: Reads[Product] = (
(JsPath \ "id").readNullable[Int] and
(JsPath \ "name").read[String] and
(JsPath \ "measure").read[Int] and
(JsPath \ "qty").read[Double].orElse(Reads.pure(0))
)(Product)
and here createProduct action:
def createProduct = DBAction(parse.json) { implicit rs =>
rs.request.body.validate[Product].map { product =>
Logger.info(s"createProduct product:$product")
//...
Ok(toJson(product))
}.recoverTotal { errors =>
BadRequest(errors.toString)
}
}
So, the qty
field has a default value 0
. If client has not sent this field, the parser needs to get a default value, but when I want try create a product, the following error appears:
JsError(List((/qty,List(ValidationError(error.path.missing,WrappedArray()))))
Following JSON client sent:
{
"measure": 1,
"name": "meat"
}
Why?, Anybody know where my mistake is?