How to return json from Play Scala controller?

2019-09-17 06:58发布

问题:

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