在通过 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 的值。
我将如何对读取进行编码,以便始终在 UserInfo 对象中创建 -1 的值,而不在正在读取的 JSON 对象中指定它?
最佳答案
使用 Reads.pure
implicit val userRead: Reads[UserInfo] = (
Reads.pure(-1L) and
(JsPath \ "firstName").readNullable[String] and
(JsPath \ "lastName").readNullable[String]
)(UserInfo.apply _)
关于json - Scala Play JSON 读取中的常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26384339/