Scala中的常量值播放JSON读取

ccu*_*ore 11 json scala playframework playframework-json

我想在通过JSON读取构造对象时使用常量值.

例如,该类将是:

case class UserInfo(
  userId: Long = -1, 
  firstName: Option[String] = None,
  lastName:  Option[String] = None
)
Run Code Online (Sandbox Code Playgroud)

阅读将是:

   implicit val userRead: Reads[UserInfo] = (
      (JsPath \ "userId").read[Long] and
      (JsPath \ "firstName").readNullable[String] and
      (JsPath \ "lastName").readNullable[String] 
    )(UserInfo.apply _)
Run Code Online (Sandbox Code Playgroud)

但我不想在JSON对象中指定userId的值.我将如何编写Reads,以便始终在UserInfo对象中创建-1的值而不在正在读取的JSON对象中指定它?

Mic*_*jac 11

使用 Reads.pure

implicit val userRead: Reads[UserInfo] = (
  Reads.pure(-1L) and
  (JsPath \ "firstName").readNullable[String] and
  (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _)
Run Code Online (Sandbox Code Playgroud)