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

2023-12-20

我正在尝试将一些相对简单的模型序列化为 json。例如,我想获取以下内容的 json 表示:

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

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


是的,自己写Format实例是推荐的方法 http://www.playframework.com/documentation/2.0.1/ScalaJson。例如,给定以下类:

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("[email protected] /cdn-cgi/l/email-protection"))
res0: User = User(1,Some,Person,Some([email protected] /cdn-cgi/l/email-protection))

scala> Json.toJson(res0)
res1: play.api.libs.json.JsValue = {"id":1,"firstName":"Some","lastName":"Person","email":"[email protected] /cdn-cgi/l/email-protection"}

scala> res1.as[User]
res2: User = User(1,Some,Person,Some([email protected] /cdn-cgi/l/email-protection))

See 文档 http://www.playframework.com/documentation/2.0.1/ScalaJsonGenerics了解更多信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 play.api.libs.json 将对象序列化为 json 的相关文章

随机推荐