且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-16 17:49:30

是的,编写自己的 Format 实例是 推荐方法.给定以下类,例如:

Yes, writing your own Format instance is the recommended approach. Given the following class, for example:

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))

有关详细信息,请参阅文档.

See the documentation for more information.