11

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?

acjay
  • 34,571
  • 6
  • 57
  • 100
ccudmore
  • 193
  • 1
  • 7

2 Answers2

11

Use Reads.pure

implicit val userRead: Reads[UserInfo] = (
  Reads.pure(-1L) and
  (JsPath \ "firstName").readNullable[String] and
  (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _)
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
0

Thanks!

I had to make one minor change to force it to a Long:

implicit val userRead: Reads[UserInfo] = (
  Reads.pure(-1:Long) and
  (JsPath \ "firstName").readNullable[String] and
  (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _)
ccudmore
  • 193
  • 1
  • 7