我有下一个代码:
package controllers.usersPage
import play.api.mvc._
import play.api.libs.json._
import model.{User, Users, Patients, CObject}
import scala.concurrent.Future
import service.{UserService}
class allUsersToJSON() extends Controller {
def convertUsersToJsonOrig(lusers: Seq[User]): JsValue = {Json.toJson(
lusers.map { u => Map("id" -> u.id, "firstName" -> u.firstName, "lastName" -> u.lastName, "email" -> u.email, "username" -> u.username, "password" -> u.password)}) }
def retAllUsers = Action { request =>
Ok( Json.stringify(convertUsersToJsonOrig(Users.listAll)))
}
}
但是,我收到了下一个错误:
$ compile
[info] Compiling 69 Scala sources and 3 Java sources to
H:\project\target\scala-2.11\classes...
[error] H:\project\app\controllers\usersPage\retrieveAllUsersJSON.scala:29: type mismatch;
[error] found : scala.concurrent.Future[Seq[model.User]]
[error] required: Seq[model.User]
[error] Ok( Json.stringify(convertUsersToJsonOrig(Users.listAll)))
[error] ^
[warn] Class com.sun.tools.xjc.Options not found - continuing with a stub.
[warn] one warning found
[error] one error found
[error] (root/compile:compileIncremental) Compilation failed
[error] Total time: 7 s, completed Apr 17, 2017 10:51:11 AM
指令Users.listAll是Future,它将为我提供一个我需要转换为JSon的User对象列表。我看到这个命令给了我scala.concurrent.Future [Seq [model.User]]数据类型。如何从此命令获取Seq [model.user],以便在convertUsersToJsonOrig中使用它? 感谢
答案 0 :(得分:3)
看看这里处理未来玩法:https://www.playframework.com/documentation/2.5.x/ScalaAsync
def retAllUsers = Action.async { request =>
for {
users <- Users.listAll
} yield Ok( Json.stringify(convertUsersToJsonOrig(users)))
}
Action
需要Request => Result
。虽然Action.async
需要Request => Future[Result]
。这允许您将未来的内容(使用map,flatMap和/或for-comprehension)转换为Result
并将其提供给框架来处理。