我想在通过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对象中指定它?
答案 0 :(得分:10)
使用Reads.pure
implicit val userRead: Reads[UserInfo] = (
Reads.pure(-1L) and
(JsPath \ "firstName").readNullable[String] and
(JsPath \ "lastName").readNullable[String]
)(UserInfo.apply _)
答案 1 :(得分:0)
谢谢!
我必须做一个小改动才能强迫它变长:
implicit val userRead: Reads[UserInfo] = (
Reads.pure(-1:Long) and
(JsPath \ "firstName").readNullable[String] and
(JsPath \ "lastName").readNullable[String]
)(UserInfo.apply _)