问题
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