Scala将对象集合写入HttpResponse

时间:2016-10-31 17:24:08

标签: scala playframework slick

我是scala初学者,现在我正在尝试构建一个基本的播放/光滑应用程序(一种用户数据库)。

似乎我已经能够建立所有的东西,但数据传输到前端。

这就是我所拥有的:

UserDAO.scala

entry: {
     'MyPackage': '\\modules\\PkgEntry.js'),
...

Application.scala

class UserDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends BaseDao {
  import driver.api._

  def entities = TableQuery[UsersTable]

  def all(): Future[Seq[User]] = {
    db.run(entities.result)
  }

  class UsersTable(tag: Tag) extends BaseTable(tag, "USER") {
    def email = column[String]("email")
    def password = column[String]("password")
    def * = (id, email, password) <> (User.tupled, User.unapply)
  }
}

UserDTO.scala

Application @Inject()(userDAO: UserDao) extends Controller {
  def users = Action.async {
    val userList = userDAO.all()
    userList
      .map { list => Ok(list.map(elem => Json.toJson(elem : UserDto))) }
      .recover { case _ => InternalServerError }
  }
}  

我不明白为什么编译器在Application.scala中抱怨case class UserDto(id: Long, login: String) object UserDto { implicit val userWriter = Json.writes[UserDto] implicit def from(user: User): UserDto = UserDto(user.id, user.login) } 。我似乎提供了转换为.map { list => Ok(list.map(elem => Json.toJson(elem : UserDto))) }所需的所有内容。可以请任何人,表明我做错了什么?

1 个答案:

答案 0 :(得分:2)

Ok(list.map(elem => Json.toJson(elem : UserDto)))替换为Json.toJson(list: Seq[UserDto])

Application @Inject()(userDAO: UserDao) extends Controller {
  def users = Action.async {
    val userList = userDAO.all()
    userList
      .map { list => Ok(Json.toJson(list: Seq[UserDto])) }
      .recover { case _ => InternalServerError }
  }
}