从数据库中获取数据以在scala中编写json格式

ikfrs5lh  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(373)

帮助我,我想从数据库中查询数据并将其保存为json格式,然后将响应发送给客户机。

implicit val locationWrites1: Writes[Location] = (
  (JsPath \ "id").write[String] and
    (JsPath \ "desc").write[String]
  ) (unlift(Location.unapply))
db.withConnection { conn =>
  val stm = conn.createStatement()
  val res = stm.executeQuery(
    """
       SELECT notes_id,notes_desc FROM notes
    """
  )
  while (res.next()) {
    Location(res.getString(1), (res.getString(2)))
  }
}
val result = Json.toJson(locationWrites1)

Ok(result)

在此处输入图像描述

vltsax25

vltsax251#

您应该先将这些位置保存在变量中。此代码只是从数据库读取数据,不将其存储在任何位置:

while (res.next()) {
 Location(res.getString(1), (res.getString(2)))
}

你必须保持这样的结果:

val locationsList = mutable.ListBuffer[Location]()
while (res.next()) {
 locationsList.append(Location(res.getString(1), (res.getString(2))))
}

然后创建一个序列格式,如下所示:

val locationSeqWrites = Writes.seq(locationWrites1)

然后将列表转换为json字符串:

val jsonResponse = locationSeqWrites.writes(locationsList).toString

相关问题