Serializing a Scala List to JSON in Play2

不羁的心 提交于 2020-01-28 04:30:13

问题


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


来源:https://stackoverflow.com/questions/17683939/serializing-a-scala-list-to-json-in-play2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!