如何从 Play Scala 控制器返回 json



我想知道如何从Play(2.2.x)Scala控制器类返回json响应数据以显示在我的视图页面上?我在Postgresql数据库中有json对象(表名:"test"和具有:id和name)。请为我提供任何解决方案。

我已经尝试了以下情况(a和b),但我不确定为什么我的控制器上没有得到响应(如:名称),所以我可以在我的视图页面上显示它们?因为我对Play/Scala和Postgresql非常陌生。案例 A.如果我给这样的:型:

def getTestValuesFromTable()   =  {
  DB.withConnection { implicit connection =>
  val selectJson =SQL("select name from test").on().apply().collect {  
            case Row(id:Long, Some(name:String)) => 
            new TestContent(name)
         }
         //.head
         //JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)
  }
  }

控制器:

def getTest = Action { 
      val response = TestContent.getTestValuesFromTable()
       Ok("Done")
      //Ok(response)
   }

输出为:完成(应用程序执行正常,没有任何异常,当然 json 数据不会来,因为我返回:仅完成,因此获得输出:"完成")

案例 B.如果我这样做:得到错误:方法应用没有足够的参数:(n:Int)模型。特征中的测试名称 线性排序优化。未指定的值参数 n。我真的不确定我怎样才能得到我的回应?

控制器:

def getTest = Action { 
      val response = TestContent.getTestValuesFromTable()
      // Ok("Done")
      Ok(response)
   }

型:

def getTestValuesFromTable(): JsValue = {
 DB.withConnection { implicit connection =>
   val selectJson = SQL("select * from test")
    JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)
    // val selectJson =SQL("select name from test").on().apply().collect {  
           // case Row(id:Long, Some(name:String)) => 
           // new TestContent(name)
        // }
         //.head
    JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)//not enough arguments for method apply: (n: Int)models.Testname in trait LinearSeqOptimized. Unspecified value parameter n.
    }
  }

请让我知道如何得到我的回复?

getJsonValuesFromTable方法不返回任何内容(Unit)。要修复它,请将此方法的定义更改为

def getJsonValuesFromTable(testContent: TestContent) = {

或显式设置类型:

def getJsonValuesFromTable(testContent: TestContent): Unit = {

此外,作为让客户端知道您正在返回 json 的下一步,您应该设置内容类型:

Ok(Json.obj(response)).as("application/json")

最新更新