【问题标题】:Adding a parameter to Implicit Reads building a case class from JSON with Play将参数添加到 Implicit Reads,使用 Play 从 JSON 构建案例类
【发布时间】:2018-10-15 14:43:10
【问题描述】:
我需要为我使用 Play 框架从 JSON 构建的案例类添加一个静态值。我可以像这样添加一个常量值:
implicit val userRead: Reads[UserInfo] = (
Reads.pure(-1L) and
(JsPath \ "firstName").readNullable[String] and
(JsPath \ "lastName").readNullable[String]
)(UserInfo.apply _)
但我看不出在调用它时如何将变量传递给隐式读取。我对 Scala 还很陌生,所以可能遗漏了一些明显的东西?
【问题讨论】:
标签:
json
scala
playframework
【解决方案1】:
我假设您的 UserInfo 是这样的:
case class UserInfo(id: Long, firstName: Option[String], lastName: Option[String])
你只需要稍微调整一下userRead:
def userRead(id: Long): Reads[UserInfo] = (
Reads.pure(id) and
(JsPath \ "firstName").readNullable[String] and
(JsPath \ "lastName").readNullable[String]
)(UserInfo.apply _)
然后在解码json的时候显式使用:
json.as[UserInfo](userRead(12345L))
或者,或者,将Reads 实例化为implicit:
implicit val userRead12345 = userRead(12345L)
json.as[UserInfo]
【解决方案2】:
有一个更简单的解决方案:
import play.api.libs.json._
在末尾添加所有具有静态默认值的值:
case class UserInfo(firstName:String, lastName:String, id:Long = -1)
将play-json format 与默认值一起使用:
object UserInfo{
implicit val jsonFormat: Format[UserInfo] = Json.using[Json.WithDefaultValues].format[UserInfo]
}
并像这样使用它
val json = Json.toJson(UserInfo("Steve", "Gailey"))
println(json.validate[UserInfo])
看这里整个example