I'd like to use a constant value when constructing an object via a JSON read.
For example the class would be:
case class UserInfo(
userId: Long = -1,
firstName: Option[String] = None,
lastName: Option[String] = None
)
And the read would be:
implicit val userRead: Reads[UserInfo] = (
(JsPath \ "userId").read[Long] and
(JsPath \ "firstName").readNullable[String] and
(JsPath \ "lastName").readNullable[String]
)(UserInfo.apply _)
But I don't want to have to specify the value for userId in the JSON object. How would I go about coding the Reads so that the value of -1 is always created in the UserInfo object without specifying it in the JSON object being read?
Use Reads.pure
implicit val userRead: Reads[UserInfo] = (
Reads.pure(-1L) and
(JsPath \ "firstName").readNullable[String] and
(JsPath \ "lastName").readNullable[String]
)(UserInfo.apply _)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With