11

通过 JSON 读取构造对象时,我想使用一个常量值。

例如,该类将是:

case class UserInfo(
  userId: Long = -1, 
  firstName: Option[String] = None,
  lastName:  Option[String] = None
)

阅读内容将是:

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

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

4

2 回答 2

11

利用Reads.pure

implicit val userRead: Reads[UserInfo] = (
  Reads.pure(-1L) and
  (JsPath \ "firstName").readNullable[String] and
  (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _)
于 2014-10-15T14:47:28.220 回答
0

谢谢!

我必须做一个小改动才能将其强制为 Long:

implicit val userRead: Reads[UserInfo] = (
  Reads.pure(-1:Long) and
  (JsPath \ "firstName").readNullable[String] and
  (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _)
于 2014-10-15T15:22:30.220 回答