How to select Single column from database using scala Play2.6

半世苍凉 提交于 2019-12-11 07:22:33

问题


I have one table User details Table and it contains below Columns

User id,username,Email

I want to select email whose user id is 1 and i want the response as in proper JSON Format

How to do that In Scala Play 2.6 with Slick
Till now I have done this

 def getPasswqord(username:String):Future[Seq[(String)]]= {
    val a2 = (sql"""select a.userpassword from user_details_table  a where a.Email=$username or a.Mobile_no=$username""".as[(String)])

    dbConfig.run(a2)

    }

from this i am getting response in a format "["12345"]".

Expected output format is

"[{"Password":"12345"}]"

回答1:


You should define custom Json Writes to format your query result. For example:

import play.api.libs.json.{JsPath, JsValue, Json, Writes}

// Given passwords
val passwords: Seq[(String)] = Seq(("12345"), ("qwerty"))
val writes : Writes[String] = (JsPath \ "password").write[String]

def toJson[T](sequence: Seq[T])(implicit writes: Writes[T]): JsValue = {
  Json.toJson(sequence)
}

toJson(passwords)(writes)

This will output json object [{"password":"12345"},{"password":"qwerty"}]



来源:https://stackoverflow.com/questions/52092178/how-to-select-single-column-from-database-using-scala-play2-6

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