![](/img/trans.png)
[英]Implicit serializing case class to Json with play.api.libs.json
[英]serializing objects to json with play.api.libs.json
我正在嘗試將一些相對簡單的模型序列化為 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但我還是有點迷茫。
是的,編寫自己的Format
實例是推薦的方法。 給定以下類,例如:
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))
有關更多信息,請參閱文檔。
由於 User 是一個案例類,您還可以執行以下操作:
implicit val userImplicitWrites = Json.writes[User]
val jsUserValue = Json.toJson(userObject)
無需編寫自己的 Format[User]。 你可以對讀取做同樣的事情:
implicit val userImplicitReads = Json.reads[User]
我在文檔中沒有找到它,這里是 api 的鏈接: http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.libs.json。 json $
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.