从数据库中获取数据以在 Scala 中写入 Json 格式

get data from database to write Json format In Scala

帮帮我,我想从数据库中查询数据并保存为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)

enter image description here

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

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