How to return json from Play Scala controller?

做~自己de王妃 提交于 2019-12-13 06:59:43

问题


I would like to know that how can I return json response data from Play(2.2.x) Scala controller class to display on my view page ? I have json objects in Postgresql database(table name: "test" and having: id and name). Please provide me any solutions for it.

I have tried the following cases(a and b), but I am not sure why I am not getting the response(like: names) on my controller, so I can show them on my view page ? since I am very new to Play/Scala and Postgresql. case a. If I give like: model:

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)
  }
  }

controller:

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

Output is: Done(application is executing fine without any exceptions, of course json data is not coming since I am returning: Done only, so getting output: "Done")

case b. If I do like this: getting error: not enough arguments for method apply: (n: Int)models.Testname in trait LinearSeqOptimized. Unspecified value parameter n. I really not sure how can I get my response for it ?

controller:

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

model:

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.
    }
  }

Please let me know how to get my response ?


回答1:


getJsonValuesFromTable method return nothing (Unit). To fix it change definition of this method to

def getJsonValuesFromTable(testContent: TestContent) = {

or explicitly setting type:

def getJsonValuesFromTable(testContent: TestContent): Unit = {

Also as a next step to let client know that you are returning json, you should set content type:

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



来源:https://stackoverflow.com/questions/35573635/how-to-return-json-from-play-scala-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!