Scala play 2 框架如何在 Json 上实现写入或格式化
Scala play 2 framework how can I implement a write or format on Json
我是 Scala 的新手,玩 2,还没有找到使用 Anorm 从数据库中 return Json 请求的方法。这是我的简单代码
def locations = Action {implicit c=>
import play.api.libs.json._
implicit val readLocations = SQL("select city,state from zips limit 1")
Ok(Json.toJson(readLocations))
}
该方法是 post 我只是想 return 通过 Json 来自数据库 table 的 1 条记录但是我得到这个错误
错误:(57, 21) Play 2 编译器:
.scala:57: 未找到类型 anorm.SqlQuery 的 Json 序列化程序。尝试为此类型实现隐式 Writes 或 Format。
好的(Json.toJson(readLocations))
欢迎任何建议,我一直在切换上面的代码,但没有任何效果。我知道我需要进行写入或格式化,但似乎不知道如何操作。
^**
您似乎正在尝试发送位置列表。你可以这样做:
def locations = Action {implicit c=>
import play.api.libs.json._
implicit val locationFmt = Json.format[Location]
case class Location(city: String, state: String)
//Send Multiple Locations if you want
val readLocations = SQL("select city,state from zips").list.map{case Row(city: String, state: String) =>
Location(city, state)
}
// Send a single Location
val readLocation = SQL("select city,state from zips limit 1").list.headOption.map{case Row(city: String, state: String) =>
Location(city, state)
}.getOrElse(throw new NoSuchElementException)
Ok(Json.toJson(readLocation))
}
我是 Scala 的新手,玩 2,还没有找到使用 Anorm 从数据库中 return Json 请求的方法。这是我的简单代码
def locations = Action {implicit c=>
import play.api.libs.json._
implicit val readLocations = SQL("select city,state from zips limit 1")
Ok(Json.toJson(readLocations))
}
该方法是 post 我只是想 return 通过 Json 来自数据库 table 的 1 条记录但是我得到这个错误 错误:(57, 21) Play 2 编译器: .scala:57: 未找到类型 anorm.SqlQuery 的 Json 序列化程序。尝试为此类型实现隐式 Writes 或 Format。 好的(Json.toJson(readLocations))
欢迎任何建议,我一直在切换上面的代码,但没有任何效果。我知道我需要进行写入或格式化,但似乎不知道如何操作。
^**
您似乎正在尝试发送位置列表。你可以这样做:
def locations = Action {implicit c=>
import play.api.libs.json._
implicit val locationFmt = Json.format[Location]
case class Location(city: String, state: String)
//Send Multiple Locations if you want
val readLocations = SQL("select city,state from zips").list.map{case Row(city: String, state: String) =>
Location(city, state)
}
// Send a single Location
val readLocation = SQL("select city,state from zips limit 1").list.headOption.map{case Row(city: String, state: String) =>
Location(city, state)
}.getOrElse(throw new NoSuchElementException)
Ok(Json.toJson(readLocation))
}