How to select Single column from database using sc

2019-07-31 19:21发布

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条回答
虎瘦雄心在
2楼-- · 2019-07-31 19:34

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

查看更多
登录 后发表回答