List to Json in Playframework Scala
-
11-06-2021 - |
Question
I am new to scala and to the playframework, but so far it is great. I am having trouble figuring out how to turn a list of data into json (or really any complex structure). This isn't a real-world example, but here is what I am trying to do. Get some data from a database.
scala> val result:List[(Long,String)] = DB.withConnection { implicit c =>
SQL("select * from users").as(
long("id")~str("uid") map(flatten)*)
}
result: List[(Long, String)] = List((3,397a73ee5150429786863db144341bb3), (4,2850760dc9024c16bea6c8c65f409821), (5,636ee2bf758e4f699f27890ac55d7db2))
I would like to be able to then turn that into json and return it. based on this doc, it looks like i need to iterate through and call toJson on the result
http://www.playframework.org/documentation/2.0/ScalaJson
But, In practice i am having trouble doing it. Is this even the correct approach? Is there some scala concept that would make this simple? I see some examples using case classes, but I haven't quite wrapped my head around that concept yet.
I don't really expect this to work but, i guess I am conceptually trying to do something like this
scala> toJson(Map("response" -> result))
<console>:27: error: No Json deserializer found for type scala.collection.immutable.Map[java.lang.String,List[(Long, String)]]. Try to implement an implicit Writes or Format for this type.
toJson(Map("response" -> result))
Thanks
Solution
As said, you can write you own implicit Writes to do that but you can also rely on the existing Writes and just retrieve your data as a List[Map[String, Any]]
and apply toJson on it:
val simple = {
get[Pk[Long]]("user.id") ~
get[Long]("user.uid") map {
case id~uid => Map("id" -> id.get.toString, "uid" -> uid.toString)
}
}
val result:List[Map(String,String)] = DB.withConnection { implicit c =>
SQL("select * from users").as(User.simple *)
}