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

Adding a parameter to Implicit Reads building a case class from JSON with Play

我需要向案例添加静态值 class 我正在使用 Play 框架从 JSON 构建。我可以像这样添加一个常量值:

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

但我看不出如何在调用变量时将变量传递给隐式读取。我是 Scala 的新手,所以可能遗漏了一些明显的东西?

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

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

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