scala - 如何在Scala Play框架中以JSON形式返回模型查询结果

标签 scala playframework playframework-2.0

我正在使用带有 scala.I 的 Play 框架 2.1.1。我查询数据库表作为列表返回到 Controller ,然后将列表转换为字符串并从 javascript 代码返回到 ajax 调用。

如何将查询结果作为json返回并通过 Controller 返回ajax调用?

应用程序.scala

import play.api._
import play.api.mvc._
import play.api.data._
import views.html._
import models._


object Application extends Controller {

  def index = Action {
    Ok(views.html.index())
  }

  def getSummaryTable = Action{
    var sum="Summary Table";
    Ok(ajax_result.render((Timesheet.getAll).mkString("\n")))
  }

  def javascriptRoutes = Action {  implicit request =>
    import routes.javascript._
    Ok(
    Routes.javascriptRouter("jsRoutes")(
          // Routes
          controllers.routes.javascript.Application.getSummaryTable

    )
    ).as("text/javascript")
  }  
}

TimeSheet.scala
// Use PostgresDriver to connect to a Postgres database
import scala.slick.driver.PostgresDriver.simple._

import scala.slick.lifted.{MappedTypeMapper,BaseTypeMapper,TypeMapperDelegate}
import scala.slick.driver.BasicProfile
import scala.slick.session.{PositionedParameters,PositionedResult}
// Use the implicit threadLocalSession
import Database.threadLocalSession
import java.sql.Date
import java.sql.Time

case class Timesheet(ID: Int, dateVal: String, entryTime: Time, exitTime: Time, someVal: String)

object Timesheet {


 //Definition of Timesheet table
 // object TS extends Table[(Int,String,Time,Time,String)]("timesheet"){
  val TSTable = new Table[Timesheet]("timesheet"){
        def ID = column[Int]("id")
        def dateVal   = column[String]("date")
        def entryTime = column[Time]("entry_time")
        def exitTime  = column[Time]("exit_time")
        def someVal = column[String]("someval")

        def * = ID ~ dateVal ~ entryTime ~ exitTime ~ someVal <> (Timesheet.apply _, Timesheet.unapply _)
   }



  def getAll: Seq[Timesheet] = { 

 Database.forURL("jdbc:postgresql://localhost:5432/my_db", "postgres", "password",null, driver="org.postgresql.Driver") withSession{
  val q = Query(TSTable)
  val qFiltered = q.filter(_.ID === 41 )
  val qDateFilter = qFiltered.filter(_.dateVal === "01/03/2013")
  val qSorted = qDateFilter.sortBy(_.entryTime)

  qSorted.list

  }
 }
}

最佳答案

另外,不要忘记为您的模型提供一个隐式(或不提供)Json 反序列化器,否则 Scala 编译器会对您大喊大叫 :-)。您可以执行以下操作:

def allTimesheet = Action {
  val timesheetWrites = Json.writes[Timesheet] // here it's the deserializer
  val listofTimeSheet = Timesheet.getAll
  Ok( Json.toJson( listofTimeSheet )( timesheetWrites ) )
}

或者您可以使用隐式,例如:
def allTimesheet = Action {
  implicit val timesheetWrites = Json.writes[Timesheet] // here it's the deserializer
  val listofTimeSheet = Timesheet.getAll
  Ok( Json.toJson( listofTimeSheet ) )
}

甚至在您的模型伴侣对象中声明您的反序列化器,例如:

伴生对象
object Timesheet {
  implicit val timesheetWrites = Json.writes[Timesheet] // here it's the deserializer
  ....
}

并在 Controller 中
import models.Timesheet.timesheetWrites

def allTimesheet = Action {
  val listofTimeSheet = Timesheet.getAll
  Ok( Json.toJson( listofTimeSheet ) )
}

关于scala - 如何在Scala Play框架中以JSON形式返回模型查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16977601/

相关文章:

scala - 如何使用封装的源和接收器测试 akka 流闭合形状可运行图

scala - 如何从 ListBuffer 中删除多个索引(快速)?

java - 将 json 对象传递给 play-framework 操作

java - Play Framework 中的发布请求中的表单值为null

java - 在 Play Framework 2.0 中将文件作为流上传

java - 如何将多个参数传递到 Play 2.0 中的模板中?

scala - 将嵌套映射中的所有键转换为 Scala 中的驼峰式大小写

scala - 如何解压 Spark DataSet 中的多个键

testing - 从 Play-Module 中进行单元测试(JPA,eclipse PersistenceProvider)

templates - 在 Play Framework 模板中的 JavaScript 中使用花括号