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
}
]
}
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.
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?
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?
// ]
// }
}
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?