gpt4 book ai didi

scala - 用列表 Play map 的scala json

转载 作者:行者123 更新时间:2023-12-02 06:02:28 25 4
gpt4 key购买 nike

我有两个类,用户和地址。

case class User(
id: Pk[Long] = NotAssigned,
name: String = "",
email: String = "",
addresses: Seq[Address])

case class Address(
id: Pk[Long] = NotAssigned,
userId: Long,
city: String)

我必须从我的 Controller 发送所有用户及其地址,例如 Map[User, List[Address]]。我可以使用 anorm (mysql) 提取它们,但随后我需要将它们作为 json 发送。能否请您帮助实现上述 Map[User, List[Address]] 的写入和读取,谢谢。

最佳答案

应该有帮助

import anorm._
import play.api.libs.json._
import play.api.libs.functional.syntax._


case class User(
id: Pk[Long] = NotAssigned,
name: String = "",
email: String = "",
addresses: Seq[Address])

case class Address(
id: Pk[Long] = NotAssigned,
userId: Long,
city: String)

// Play does not provide Format[Pk[A]], so you need to define it
implicit def pkReads[A](implicit r: Reads[Option[A]]): Reads[Pk[A]] = r.map { _.map(Id(_)).getOrElse(NotAssigned) }
implicit def pkWrites[A](implicit w: Writes[Option[A]]): Writes[Pk[A]] = Writes(id => w.writes(id.toOption))

implicit val addrFormat = Json.format[Address]
implicit val userFormat = Json.format[User]

现在您可以轻松地序列化用户:

val as = Seq(Address(Id(2), 1, "biim"))
val u = User(Id(1), "jto", "jto@foo.bar", as)

scala> Json.toJson(u)
res6: play.api.libs.json.JsValue = {"id":1,"name":"jto","email":"jto@foo.bar","addresses":[{"id":2,"userId":1,"city":"biim"}]}

正如 Julien 所说,您不能只序列化一个 Map[User, Seq[Address]]。它只是没有意义,因为 User 不能是 Json 对象中的键。

关于scala - 用列表 Play map 的scala json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com