帮帮我,我想从数据库中查询数据并将其保存为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)
最佳答案
您应该首先将位置保存在变量中。此代码只是从数据库读取数据,而不将其存储在任何地方:
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
关于mysql - Scala中从数据库获取数据写入Json格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428527/