Json Writes in Play 2.1.1

I recently started using Playframework and am implementing the site using Play 2.1.1 and Slick 1.0.0. Now I'm trying to wrap my head around Json Writes, as I want to return Json to one of my controllers.

I watched several links on this topic (for example this and this one , but cannot understand what I am doing wrong.

I have a model that looks like this:

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 _) } 

You can see the implicit val I'm trying to use, but when I try to return Json to my controller by doing this:

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

I am still facing this error:

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

I tried several other ways to implement Writes. For example, I tried the following instead of the implicit val value above:

 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] ) 

}

Can anyone point me in the right direction?

+4
source share
1 answer

JSON Inception to the rescue! You need to write

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

What is it. No need to write your own Reads and Writes anymore thanks to Scala 2.10 macro magic. (I recommend that you read the playback documentation for Working with JSON , this explains a lot.)

Edit: I did not notice that you already have Json.format inside the AreaZipcodes object. You need to either move this line from AreaZipcodes or import it into the current context, i.e.

 import AreaZipcodes.areaZipcodeFormat 
+11
source

Source: https://habr.com/ru/post/1485585/


All Articles