mysql - Scala中从数据库获取数据写入Json格式

标签 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

最佳答案

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

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/

相关文章:

c# - 插入多行的最快方法

java - REST API - 对不同的参数使用相同的 URI 和相同的方法来调用不同的方法

Spring Boot SSL 客户端

javascript - 如何从 API 调用中获取响应 JSON

scala - 如何使用 Scala Breeze 对向量执行逐元素标量运算?

scala - 如何将路径列表传递给 spark.read.load?

以逗号分隔列表形式返回的 MySQL 列数据

mysql - 如何选择某列数据不重复的行-SQL

php - 使用数组 SQL 获取 ID

scala - 在 Scala 中,元组语法是语言本身的一部分还是 TupleN 上的隐式构造函数调用?