在Play框架中,我使用Slick和MySQL数据库,如何将查询结果( Future [Seq [SomeClass]] )转换为Json,以便在jQuery Autocomplete中进一步使用。我可以序列化 SomeClass ,但我应该在哪里使用 .map (或其他内容)?
加:
型号:
package models
import play.api.libs.json._
case class Equipment(id: Long, name: String,area: String,kiMin: Double,kiMax: Double,cosFiMin: Double,cosFiMax: Double){
implicit val equipmentWrites = new Writes[Equipment] {
def writes(equipment: Equipment) = Json.obj(
"id" -> equipment.id,
"name" -> equipment.name,
"area" -> equipment.area,
"kiMin" -> equipment.kiMin,
"kiMax" -> equipment.kiMax,
"cosFiMin" -> equipment.cosFiMin,
"cosFiMax" -> equipment.cosFiMax
)
//also tried this for Seq
/* def writes(equipment: Equipment): JsValue = {
val equipmentSeq = Seq(
"id" -> JsNumber(equipment.id),
"name" -> JsString(equipment.name),
"area" -> JsString(equipment.area),
"kiMin" -> JsNumber(equipment.kiMin),
"kiMax" -> JsNumber(equipment.kiMax),
"cosFiMin" -> JsNumber(equipment.cosFiMin),
"cosFiMax" -> JsNumber(equipment.cosFiMax)
)
JsObject(equipmentSeq)
}*/
}
}
控制器:
def auto(term: String) = Action {
Ok(Json.toJson(equipmentDAO.get(term)))
}
DAO:
def get(name: String): Future[Seq[Equipment]] = db.run((equipment.filter { _.name === name }).result)
Added2:
控制器方法:
def auto(term: String) = Action.async {
val future: Future[Seq[Equipment]] = equipmentDAO.get(term)
future.map { seqOfSomeClass =>
Ok(Json.toJson(seqOfSomeClass))
}
}
串行:
implicit val equipmentWrites: Writes[Equipment] = (
(JsPath \ "id").write[Long] and
(JsPath \ "name").write[String] and
(JsPath \ "area").write[String] and
(JsPath \ "kiMin").write[Double] and
(JsPath \ "kiMax").write[Double] and
(JsPath \ "cosFiMin").write[Double] and
(JsPath \ "cosFiMax").write[Double]
)(unlift(Equipment.unapply))
答案 0 :(得分:4)
考虑到您了解Play Framework handles JSON的Reads
and Writes
以及SomeClass
已有serve a list of SomeClass
in JSON的内容,您可以在控制器中执行以下操作:
def someAction = Action.async {
val future: Future[Seq[SomeClass]] = ??? // get the future using Slick
future.map { seqOfSomeClass =>
Ok(Json.toJson(seqOfSomeClass))
}
}