繁体   English   中英

Scala中的常量值播放JSON读取

[英]Constant value in Scala Play JSON Reads

我想在通过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对象中指定它?

使用Reads.pure

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

谢谢!

我不得不进行一次小改动以强迫它变长:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM