我正在尝试将列表列表转换为Json。到目前为止,我能够将第一个项目转换为Json,但是如何为整个列表执行此操作?
目前我有以下内容:
def jsonAll = DBAction { implicit rs =>
val list = Performances.listAll
val w = Json.obj(
"items" -> Json.arr(
Json.obj("performance" -> list(0)._1),
Json.obj("location" -> list(0)._2),
Json.obj("user" -> list(0)._3)
)
)
Ok(Json.toJson(w))
}
'list'定义为:
def listAll: List[(Performance, Location, DBUser)] = {
...
}
注意:您还必须定义单个对象的格式。
implicit val performanceFormat = Json.format[Performance]
implicit val locationFormat = Json.format[Location]
implicit val userFormat = Json.format[DBUser]
答案 0 :(得分:2)
您是否考虑过使用自己的演出类型并使用Json.toJson
?
case class Performance(performance: String, location: String, user: String)
implicit val performancesWrites = new Writes[Performance] {
def writes(p: Performance) = Json.obj(
"performance" -> p.performance,
"location" -> p.location,
"user" -> p.user
)
}
val list = List(("hi", "there", "buddy"), ("meep", "eleven", "foobar"))
val performances = list.map((Performance.apply _) tupled)
val resultingJson = Json.toJson(performances)
// Yields: [{"performance":"hi","location":"there","user":"buddy"},{"performance":"meep","location":"eleven","user":"foobar"}]
答案 1 :(得分:0)
所以更多的研究和潜入Scala的奇怪世界(我来自Java)我找到了解决方案:
def jsonAll = DBAction { implicit rs =>
val list = Performances.listAll
val re = list.map(
iter =>
Json.obj(
"performance" -> iter._1,
"location" -> iter._2,
"user" -> iter._3
)
)
Ok(Json.toJson(re))
}
一旦你知道语法就很简单:|