【问题标题】:get data from database to write Json format In Scala从数据库中获取数据以在 Scala 中写入 Json 格式
【发布时间】:2018-11-22 10:10:55
【问题描述】:

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

【问题讨论】:

  • 问题出在哪里?
  • 我无法从查询中检索数据。保存成json格式发送给客户端

标签: mysql scala rest playframework


【解决方案1】:

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

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

【讨论】:

  • locationsList.append 不起作用,它的消息错误是“无法解析符号附加”
  • 我编辑了答案。它应该是可变的。ListBuffer[Location]()
  • 非常感谢您对我的帮助。^_^
  • 您有资源可以了解更多信息吗?我对此感兴趣并想了解更多信息。
猜你喜欢
  • 2016-12-08
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 2019-09-26
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多