使用play.api.libs.json将对象序列化为json [英] serializing objects to json with play.api.libs.json

查看:454
本文介绍了使用play.api.libs.json将对象序列化为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to serialize some relatively simple models into json. For example, I'd like to get the json representation of:

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但我还是有点迷茫.

Do i need to write my own Format[User] with the appropriate reads and writes methods or is there some other way? I've looked at https://github.com/playframework/Play20/wiki/Scalajson but I'm still a bit lost.

推荐答案

是的,编写自己的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(""))
}

该实例可能看起来像这样:

The instance might look like this:

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.

这篇关于使用play.api.libs.json将对象序列化为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆