[英]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宏的神奇功能,不再需要编写自己的Reads
和Writes
。 (我建议您阅读Play的“ 使用JSON”文档,其中有很多解释。)
编辑:我没有注意到你已经有Json.format
里面AreaZipcodes
对象。 您需要将该行移出AreaZipcodes
或将其导入到当前上下文中,即
import AreaZipcodes.areaZipcodeFormat
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.