将参数添加到隐式读取,使用 Play 从 JSON 构建案例类



我需要为我正在使用Play框架从JSON构建的案例类添加一个静态值。我可以添加一个常量值,如下所示:

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

但是我看不出如何在调用变量时将变量传递到隐式读取中。我对 Scala 很陌生,所以可能错过了一些明显的东西?

我假设你的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]

有一个更简单的解决方案:

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])

在这里查看整个示例

最新更新