【发布时间】:2022-01-26 18:14:57
【问题描述】:
因为我在 Redis 中将数据保存为 json,所以当我从其他服务获取数据时,我需要将 json 解析为服务类型。我将举一个有效的例子:
case class Item(id: Int, name: String)
object Item {
import play.api.libs.json._
implicit val read = Json.reads[Item]
implicit val write = Json.writes[Item]
def tupled = (Item.apply _).tupled
}
object RedisService {
...
def get(key: String): Option[JsValue] =
client.get(key).map(Json.parse(_))
}
object Service1 {
val data = RedisService.get("service1")
data match {
case Some(json) => val items = json.as[List[Item]]
case None =>
}
}
..
object Service9 {
val data = RedisService.get("service9")
data match {
case Some(json) => val items = json.as[List[Item]]
case None =>
}
}
优化类型(我正在尝试但得到隐含错误)
object RedisService {
...
def get[A](key: String): Option[A] =
client.get(key).map(x => Json.parse(x).as[A]) // no implicits found for parameter Reads[A]
}
object Service1 {
val data = RedisService.get[List[Item]]("service1")
data match {
case Some(items) => // avoid using conversion in all services
case None =>
}
}
【问题讨论】:
标签: scala generics playframework