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

时间:2018-11-22 10:10:56

标签: mysql scala rest playframework

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

1 个答案:

答案 0 :(得分:0)

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

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))))
}

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

 val locationSeqWrites = Writes.seq(locationWrites1)

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

val jsonResponse = locationSeqWrites.writes(locationsList).toString