简体   繁体   English

在Playframework Scala中列出Json

[英]List to Json in Playframework Scala

I am new to scala and to the playframework, but so far it is great. 我是scala和playframework的新手,但到目前为止它很棒。 I am having trouble figuring out how to turn a list of data into json (or really any complex structure). 我无法弄清楚如何将数据列表转换为json(或实际上任何复杂的结构)。 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. 我希望能够将其变成json并将其返回。 based on this doc, it looks like i need to iterate through and call toJson on the result 基于这个文档,看起来我需要遍历并在结果上调用toJson

http://www.playframework.org/documentation/2.0/ScalaJson 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? 是否有一些scala概念会使这个变得简单? 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 谢谢

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: 如上所述,您可以编写自己的隐式Write来执行此操作,但您也可以依赖现有的Writes,只需将数据检索为List[Map[String, Any]]并在其上应用toJson:

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 *)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM