I am trying to return JSON response data from Postgresql database using Play framework(Scala).
I have tried the following where I am not able to return my json response output.
I have couple of JSON objects in my database table: jsondata
, which is having id
and name
. I have written some println messages, those are coming as None, don't know why ?
The compiler error says
Missing parameter either [id] or [name]
I am not sure what I am doing wrong in my code to get JSON response output for my JSON objects from database(controller and model).
controller:
import play.api.Play.current
import play.mvc.Controller;
import play.libs.Json;
import play.libs.Json.*;
import com.fasterxml.jackson.databind.JsonNode;
import org.codehaus.jackson.JsonNode;
import models.Getjsondata
import com.google.gson.Gson
import scala.util.{Try, Success, Failure}
Getjsondata.getJsonValues(Getjsondata(Json.parse(id)), Json.parse(name));
class MyController extends Controller {
def getJson = Action { request =>
println("calling getJson ... !!")//getting this message on play console
val body: Anyname = request.body
val textBody: Option[String] = body.asText
println("body: "+body);//AnyContentAsEmpty
println("textBody: "+textBody);//None
val optionJson = textBody.flatMap(json => Try(Json.parse(json)).toOption)
val bodyId = optionJson.map(_ \ "id")
val bodyname = optionJson.map(_ \ "name")
println("bodyId: "+bodyId);//None
println("bodyName: "+bodyName);//None
println("optionJson: "+optionJson);//None
{
for {
id <- bodyId
name <- bodyname
json <- optionJson
} yield {
println("calling getJson else ... !!")
val response = Getjsondata.getJsonValues(Getjsondata(id.as[Long],name.as[String]));
Ok("Json data retrieved successfully: "+response)
}
} getOrElse BadRequest("Missing parameter either [id] or [name]")//giving error, not executing the above for loop
}
}
model:
import anorm._
import anorm.SqlParser._
import play.api.db._
import play.api.Play.current
import play.api.libs.json.{Json,JsValue}
import play.api.db.DB
import play.api.libs.json._
import anorm.~
import play.api.libs.functional.syntax._
case class Getjsondata (
id: Pk[Long], name: String
)
object Getjsondata {
val extractor = {
get[Pk[Long]]("jsondata.id") ~
get[String]("jsondata.name") map {
case id~name => Getjsondata(id, name)
}
}
def getJsonValues(jsondata: Getjsondata): List[Getjsondata]= {
println("addJson getJsonValues page... !")
DB.withConnection { implicit connection =>
// SQL("select row_to_json(jsondata) from jsondata");
SQL("select * from jsondata");
}
}
}