如何在scala play框架中将模型查询结果作为JSON返回

Ram*_*sad 2 scala playframework playframework-2.0

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

如何将查询结果作为json返回并通过控制器返回到ajax调用?

Application.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")
  }  
}
Run Code Online (Sandbox Code Playgroud)

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

  }
 }
}
Run Code Online (Sandbox Code Playgroud)

tre*_*nik 6

另外,不要忘记为您的模型提供隐式(或不是)Json反序列化器,否则,Scala编译器会对您大喊:-).你可以这样做:

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

或者您可以使用如下隐含:

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

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

伴侣对象

object Timesheet {
  implicit val timesheetWrites = Json.writes[Timesheet] // here it's the deserializer
  ....
}
Run Code Online (Sandbox Code Playgroud)

并在控制器中

import models.Timesheet.timesheetWrites

def allTimesheet = Action {
  val listofTimeSheet = Timesheet.getAll
  Ok( Json.toJson( listofTimeSheet ) )
}
Run Code Online (Sandbox Code Playgroud)


bis*_*ros 5

我建议你使用play.api.libs.Json.toJson.

这是一个例子:

object Products extends Controller {
  def list = Action {
  val productCodes = Product.findAll.map(_.ean)
  Ok(Json.toJson(productCodes))
}
Run Code Online (Sandbox Code Playgroud)

Json.toJson返回一个JsValuePlay将自动添加application/json标题.

请参阅Play for Scala第8章.