Json在Play 2.1.1中写道

gor*_*row 4 json scala playframework playframework-2.1

我最近开始使用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 _)
}
Run Code Online (Sandbox Code Playgroud)

您可以看到我正在尝试使用的隐式val,但是当我尝试通过执行以下操作返回控制器中的Json时:

Ok(Json.toJson(areas.map(a => Json.toJson(a))))
Run Code Online (Sandbox Code Playgroud)

我在某种程度上仍然面临着这个错误消息:

No Json deserializer found for type models.AreaZipcode. Try to implement an implicit     Writes or Format for this type. 
Run Code Online (Sandbox Code Playgroud)

我已经尝试了其他几种方法来实现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]
    )
Run Code Online (Sandbox Code Playgroud)

}

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

Car*_*ten 11

JSON开始抢救!你只需要写

import play.api.libs.json._
implicit val areaZipcodeFormat = Json.format[AreaZipcode]
Run Code Online (Sandbox Code Playgroud)

而已.无需编写自己ReadsWrites了,感谢斯卡拉2.10宏的魔力.(我建议您阅读Play有关使用JSON的文档,它解释了很多.)

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

import AreaZipcodes.areaZipcodeFormat
Run Code Online (Sandbox Code Playgroud)