[英]Scala vector to case class
I want to map this result query that showed vector
to case class
我想将这个显示vector
结果查询映射到case class
dal:达尔:
def selectPerson = sql"select * from PERSON".as[(String,String)]
service:服务:
def ListPerson: Future[Seq[(String,String)]] = {
db.run(GroupDealerDetailDal.selectPerson)
}
controller:控制器:
def listPerson = Action.async { implicit request =>
GroupDealerDetailService.ListPerson.map(result =>
Ok(Json.toJson(result.toString)))
}
case class:案例类:
case class Person(username: String, password: String)
object Person {
implicit val personFormat = Json.format[Person]
}
the result is Vector((prastyo,12345))
结果是Vector((prastyo,12345))
how can I map that result to case class Person
我如何将该结果映射到case class Person
so the result is {"username" : "prastyo", "password" : "12345"}
所以结果是{"username" : "prastyo", "password" : "12345"}
It sounds like you want JSON output, so I suspect that the inner part should be something like this (not tested):听起来您想要 JSON 输出,所以我怀疑内部部分应该是这样的(未测试):
GroupDealerDetailService.ListPerson.map { people => Ok(
Json.toJson(
people map { case (username, password) =>
Person(username, password)
}
)
)}
If you want map DB result to Json response, you dont need extra case class
and transformations.如果要将 DB 结果映射到 Json 响应,则不需要额外的case class
和转换。 You may use coast-to-coast design with Json writes combinators.您可以将海岸到海岸设计与 Json 编写组合器一起使用。
Simple writes简单写入
val u: OWrites[(String, String)] = (
(__ \ "username").write[String] and
(__ \ "password").write[String]
).tupled
map your (String, String)
to JsObject
.将您的(String, String)
映射到JsObject
。
u.writes("prastyo" -> "12345")
res17: play.api.libs.json.JsObject = {"username":"prastyo","password":"12345"}
With Writes.traversableWrites
使用Writes.traversableWrites
val s = Writes.seq(u)
you can map your Vector
to JsArray
你可以将你的Vector
映射到JsArray
s.writes(Seq("prastyo" -> "12345"))
res16: play.api.libs.json.JsValue = [{"username":"prastyo","password":"12345"}]
complete controller:完整的控制器:
def listPerson = Action.async {
GroupDealerDetailService.ListPerson.map(s.writes).map(Ok(_))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.