簡體   English   中英

傑森(Json)在Play 2.1.1中寫作

[英]Json Writes in Play 2.1.1

我最近開始使用Playframework,並且正在使用Play 2.1.1和Slick 1.0.0來實現一個站點。 我現在想把頭放在Json Writes上,因為我想在我的一個控制器中返回Json。

我一直在尋找關於該主題的幾處參考資料(例如這一這一參考資料,但無法弄清楚我在做什么錯。

我有一個看起來像這樣的模型:

case class AreaZipcode(  id: Int,
                     zipcode: String,
                     area: String,
                     city: String
                    )

object AreaZipcodes extends Table[AreaZipcode]("wijk_postcode") {

    implicit val areaZipcodeFormat = Json.format[AreaZipcode]

    def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    def zipcode = column[String]("postcode", O.NotNull)
    def area = column[String]("wijk", O.NotNull)
    def city = column[String]("plaats", O.NotNull)

    def autoInc = * returning id

    def * = id ~ zipcode ~ area ~ city <> (AreaZipcode.apply _, AreaZipcode.unapply _)
}

您可以看到我要使用的隱式val,但是當我嘗試通過執行以下操作在控制器中返回Json時:

Ok(Json.toJson(areas.map(a => Json.toJson(a))))

我仍然以某種方式仍然遇到此錯誤消息:

No Json deserializer found for type models.AreaZipcode. Try to implement an implicit     Writes or Format for this type. 

我嘗試了幾種其他方式來實現Writes。 例如,我嘗試了以下方法,而不是上面的隱式val:

implicit object areaZipcodeFormat extends Format[AreaZipcode] {

    def writes(a: AreaZipcode): JsValue = {
      Json.obj(
        "id" -> JsObject(a.id),
        "zipcode" -> JsString(a.zipcode),
        "area" -> JsString(a.area),
        "city" -> JsString(a.city)
      )
    }
    def reads(json: JsValue): AreaZipcode = AreaZipcode(
      (json \ "id").as[Int],
      (json \ "zipcode").as[String],
      (json \ "area").as[String],
      (json \ "city").as[String]
    )

}

有人可以指出正確的方向嗎?

營救JSON Inception 你只需要寫

import play.api.libs.json._
implicit val areaZipcodeFormat = Json.format[AreaZipcode]

而已。 借助Scala 2.10宏的神奇功能,不再需要編寫自己的ReadsWrites (我建議您閱讀Play的“ 使用JSON”文檔,其中有很多解釋。)

編輯:我沒有注意到你已經有Json.format里面AreaZipcodes對象。 您需要將該行移出AreaZipcodes或將其導入到當前上下文中,即

import AreaZipcodes.areaZipcodeFormat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM