Serializing a Scala List to JSON in Play2

2020-02-08 16:10发布

问题:

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?

回答1:

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}]}