使用play.api.libs.json将对象序列化为json

时间:2012-08-16 01:47:24

标签: json scala playframework playframework-2.0 playframework-json

我正在尝试将一些相对简单的模型序列化为json。例如,我想得到json表示:

case class User(val id: Long, val firstName: String, val lastName: String, val email: Option[String]) {
    def this() = this(0, "","", Some(""))
}

我是否需要使用适当的读写方法编写自己的格式[用户],还是有其他方法吗?我看了https://github.com/playframework/Play20/wiki/Scalajson,但我还是有点失落。

2 个答案:

答案 0 :(得分:22)

是的,编写自己的Format实例是the recommended approach。给定以下类,例如:

case class User(
  id: Long, 
  firstName: String,
  lastName: String,
  email: Option[String]
) {
  def this() = this(0, "","", Some(""))
}

实例可能如下所示:

import play.api.libs.json._

implicit object UserFormat extends Format[User] {
  def reads(json: JsValue) = User(
    (json \ "id").as[Long],
    (json \ "firstName").as[String],
    (json \ "lastName").as[String],
    (json \ "email").as[Option[String]]
  )

  def writes(user: User) = JsObject(Seq(
    "id" -> JsNumber(user.id),
    "firstName" -> JsString(user.firstName),
    "lastName" -> JsString(user.lastName),
    "email" -> Json.toJson(user.email)
  ))
}

你会像这样使用它:

scala> User(1L, "Some", "Person", Some("s.p@example.com"))
res0: User = User(1,Some,Person,Some(s.p@example.com))

scala> Json.toJson(res0)
res1: play.api.libs.json.JsValue = {"id":1,"firstName":"Some","lastName":"Person","email":"s.p@example.com"}

scala> res1.as[User]
res2: User = User(1,Some,Person,Some(s.p@example.com))

有关详细信息,请参阅the documentation

答案 1 :(得分:8)

由于User是一个案例类,你也可以这样做:

implicit val userImplicitWrites = Json.writes[User]
val jsUserValue = Json.toJson(userObject)

无需编写自己的格式[用户]。您可以对读取执行相同的操作:

implicit val userImplicitReads = Json.reads[User]

我没有在文档中找到它,这里是api的链接:http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.libs.json.Json $