Có, viết ví dụ Format
của riêng bạn là the recommended approach. Căn cứ vào lớp sau, ví dụ:
case class User(
id: Long,
firstName: String,
lastName: String,
email: Option[String]
) {
def this() = this(0, "","", Some(""))
}
Các ví dụ có thể trông như thế này:
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)
))
}
Và bạn muốn sử dụng nó như thế này:
scala> User(1L, "Some", "Person", Some("[email protected]"))
res0: User = User(1,Some,Person,Some([email protected]))
scala> Json.toJson(res0)
res1: play.api.libs.json.JsValue = {"id":1,"firstName":"Some","lastName":"Person","email":"[email protected]"}
scala> res1.as[User]
res2: User = User(1,Some,Person,Some([email protected]))
Xem the documentation để biết thêm thông tin .
Nguồn
2012-08-16 02:39:50
Fantastic, cảm ơn! Và nếu tôi muốn một Seq [User] là Json thì sao? :) – LuxuryMode
Chơi đi kèm với một thể hiện cho 'Seq', vì vậy bạn chỉ có thể sử dụng' Json.toJson (người dùng) .as [Seq [User]] '. –
Sử dụng 'JsNumber' của Play với Mongo, tôi nhận được lỗi serialization:' [error] play - Không thể gọi hành động, cuối cùng cũng gặp lỗi: java.lang.IllegalArgumentException: không thể tuần tự hóa lớp scala.math.BigDecimal' –