如何编写Scala控制器类以返回JSON响应?

时间:2016-02-24 09:19:26

标签: json postgresql scala playframework

我目前正在使用Play框架应用程序(版本:2.2.x)学习Scala。

从postgresql数据库表(测试)获取JSON响应的最佳方法是什么?

我已经完成了以下路径(Unable to return JSON response using Play Framework and Postgresql?)并尝试了另一种方法,但不幸的是我无法获取json,并且缺少参数类型错误,我不确定代码是否正常?

控制器:

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)

 }
}

模型:

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

错误:

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) 

0 个答案:

没有答案