在 Play2 中将 Scala 列表序列化为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17683939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:30:32  来源:igfitidea点击:

Serializing a Scala List to JSON in Play2

jsonscalaplayframeworkplayframework-2.0

提问by Johan Paul

I am trying to deserialize a list of Scala objects to a JSON map in Play2 - a pretty trivial use case with JSON, I'd say. My JSON output would be something along the lines of:

我正在尝试将 Scala 对象列表反序列化为 Play2 中的 JSON 映射 - 我会说这是一个非常简单的 JSON 用例。我的 JSON 输出将类似于以下内容:

{
    "users": [
        {
            "name": "Example 1",
            "age": 20
        },
        {
            "name": "Example 2",
            "age": 42
        }
    ]
}

To achieve this I am looking at the Play2's JSON documentation titled "The Play JSON library". To me their examples are pretty trivial, and I've confirmed that they work for me. Hence, I am able to deserialize a single Userobject properly.

为了实现这一点,我正在查看名为“The Play JSON library”的 Play2 的 JSON 文档。对我来说,他们的例子是微不足道的,我已经确认他们对我有用。因此,我能够User正确反序列化单个对象。

But making a map containing a list in JSON seems a bit verbose in Play2, when I read the documentation. Is there something I am not grokking?

但是,当我阅读文档时,在 Play2 中制作包含 JSON 列表的地图似乎有点冗长。有什么我不喜欢的吗?

This is basically my simple Scala code:

这基本上是我的简单 Scala 代码:

case class User(name: String, age: Int)

object UserList {
  implicit val userFormat = Json.format[User]  

  val userList = List(User("Example 1", 20), User("Example 2", 42))
  val oneUser = Json.toJson(userList(0)) // Deserialize one Scala object properly to JSON.
  // JSON: { "user" : [ <-- put content of userList here. How?
  //                  ]
  //       }
}

So my question would be; how can I transform the content of the userListList above to a hash in the JSON in a more generic way than explicitly writing out each hash element, as the Play documentation suggests?

所以我的问题是;userList正如 Play 文档所建议的那样,如何以比显式写出每个哈希元素更通用的方式将上面 List的内容转换为JSON 中的哈希?

回答by Ionu? G. Stan

scala> import play.api.libs.json._
import play.api.libs.json._

scala> case class User(name: String, age: Int)
defined class User

scala> implicit val userFormat = Json.format[User]
userFormat: play.api.libs.json.OFormat[User] = play.api.libs.json.OFormat$$anon@38d2c662

scala> val userList = List(User("Example 1", 20), User("Example 2", 42))
userList: List[User] = List(User(Example 1,20), User(Example 2,42))

scala> val users = Json.obj("users" -> userList)
users: play.api.libs.json.JsObject = {"users":[{"name":"Example 1","age":20},{"name":"Example 2","age":42}]}