4

我最近开始使用 Playframework,并且正在使用 Play 2.1.1 和 Slick 1.0.0 实现一个站点。我现在正试图围绕 Json 写入,因为我想在我的一个控制器中返回 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. 

我尝试了其他几种方法来实现写入。例如,我尝试了以下方法,而不是上面的隐式 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]
    )

}

有人可以指出我正确的方向吗?

4

1 回答 1

11

JSON 启动救援!你只需要写

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

就是这样。借助 Scala 2.10 宏的魔力,无需再编写自己的Reads代码。Writes(我建议你阅读 Play 关于使用 JSON的文档,它解释了很多。)

编辑: 我没有注意到你已经拥有了物体的Json.format内部。AreaZipcodes您要么需要将该行移出AreaZipcodes或将其导入当前上下文,即

import AreaZipcodes.areaZipcodeFormat
于 2013-06-11T09:56:32.910 回答