I am currently learning Scala with a Play framework application (version:2.2.x).
What'd be the best way to fetch a JSON response from a postgresql database table(test)?
I have done the following trails(Unable to return JSON response using Play Framework and Postgresql?) and trying another approach here, but unfortunately I am unable to fetch json, and getting missing parameter type error, I am not sure whether the code is fine or not ?
controller:
class Test extends Controller {
implicit val testContentWrites: Writes[TestContent] = (
(JsPath \ "id").write[Long] and
(JsPath \ "name").write[String]
)(unlift(TestContent.unapply))
implicit val testContentReads: Reads[TestContent] = (
(JsPath \ "id").read[Long] and
(JsPath \ "name").read[String]
)(TestContent.apply _)
def getTest = Action { request =>
val response = Getjsoncontent.getJsonValuesFromTable()
Ok(response)
}
}
model:
case class TestContent(id: Long, name: String)
object TestContent = {
def getJsonValuesFromTable(): JsValue={
DB.withConnection { implicit connection =>
val selectJson = SQL("select * from test")
JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)//here I am getting the json data which is stored in my database on my console like as a Runtime Exception: 500 Internal Server Error
}
}
Error:
Execution Exception:
[RuntimeException: Left(TypeDoesNotMatch(Cannot convert "{\r\n \"title\" : -------------------------------------\r\n": class org.postgresql.util.PGobject to String for column ColumnName(test.name,Some(name))))]
at line: JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)