在 Play2 中将 Scala 列表序列化为 JSON [英] Serializing a Scala List to JSON in Play2
问题描述
我正在尝试将 Scala 对象列表反序列化为 Play2 中的 JSON 映射 - 我会说这是一个非常简单的 JSON 用例.我的 JSON 输出类似于以下内容:
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:
{
"users": [
{
"name": "Example 1",
"age": 20
},
{
"name": "Example 2",
"age": 42
}
]
}
为了实现这一点,我正在查看标题为 Play JSON 库" 的 Play2 的 JSON 文档.对我来说,他们的例子是微不足道的,我已经确认他们对我有用.因此,我能够正确反序列化单个 User
对象.
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 User
object properly.
但是当我阅读文档时,在 Play2 中制作包含 JSON 列表的地图似乎有点冗长.有什么我不喜欢的吗?
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?
这基本上是我的简单 Scala 代码:
This is basically my simple Scala code:
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?
// ]
// }
}
所以我的问题是;我怎样才能以比明确写出每个哈希元素更通用的方式将上面的 userList
列表的内容转换为 JSON 中的哈希,正如 Play 文档所建议的那样?
So my question would be; how can I transform the content of the userList
List above to a hash in the JSON in a more generic way than explicitly writing out each hash element, as the Play documentation suggests?
推荐答案
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$1@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}]}
这篇关于在 Play2 中将 Scala 列表序列化为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!