【问题标题】:Scala play 2 framework how can I implement a write or format on JsonScala play 2 框架如何在 Json 上实现写入或格式
【发布时间】:2015-05-16 18:09:48
【问题描述】:

我是 Scala 的新手并玩过 2,但还没有找到使用 Anorm 从数据库返回 Json 请求的方法。这是我的简单代码

  def locations = Action {implicit c=>
import play.api.libs.json._
 implicit val readLocations = SQL("select city,state from zips limit 1")

  Ok(Json.toJson(readLocations))
 }

该方法是一个帖子,我只是想通过 Json 1 记录从那里的数据库表中返回,但我收到此错误 错误:(57, 21) Play 2 编译器: .scala:57:找不到类型 anorm.SqlQuery 的 Json 序列化程序。尝试为此类型实现隐式写入或格式。 好的(Json.toJson(readLocations))

欢迎提出任何建议,我一直在切换上面的代码,但没有任何效果。我知道我需要进行写入或格式化,但似乎不知道如何操作。

                 ^**

【问题讨论】:

  • 首先您必须运行Anorm docs 中提到的查询。然后,您将拥有一个可以序列化为 json 的类型(您需要该类型的 ReadsFormat)。顺便说一句,强烈推荐阅读Play docs concerning JSON

标签: json scala playframework-2.0


【解决方案1】:

您似乎正在尝试发送位置列表。你可以这样做:

  def locations = Action {implicit c=>
    import play.api.libs.json._
    implicit val locationFmt = Json.format[Location]

    case class Location(city: String, state: String)

    //Send Multiple Locations if you want
    val readLocations = SQL("select city,state from zips").list.map{case Row(city: String, state: String) =>
      Location(city, state)
    }

    // Send a single Location
    val readLocation = SQL("select city,state from zips limit 1").list.headOption.map{case Row(city: String, state: String) =>
      Location(city, state)
    }.getOrElse(throw new NoSuchElementException)

    Ok(Json.toJson(readLocation))
  }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-03-20
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2016-07-08
相关资源
最近更新 更多