Rendering JSON with Play! and Scala
json, playframework, playframework-2.0, scala
Solution
I really recommend to upgrade to play 2.1-RC1 because here, JSON writers/readers are very simple to be defined (more details here)
But in order to help you to avoid some errors, I will give you a hint with imports: - use these imports only! (notice that json.Reads is not included)
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Writes._
and you only have to write this code for write/read your class to/from Json (of course you will have `User` instead of `Address`:
implicit val addressWrites = Json.writes[Address]
implicit val addressReads = Json.reads[Address]
Now, they will be used automatically:
Example of write:
Ok(Json.toJson(entities.map(s => Json.toJson(s))))
Example of read(I put my example of doing POST for creating an entity by reading json from body) please notice `addressReads` used here
def create = Action(parse.json) { request =>
request.body.validate(addressReads).map { entity =>
Addresses.insert(entity)
Ok(RestResponses.toJson(RestResponse(OK, "Succesfully created a new entity.")))
}.recover { Result =>
BadRequest(RestResponses.toJson(RestResponse(BAD_REQUEST, "Unable to transform JSON body to entity.")))
}
}
In conclusion, they tried (and succeded) to make things very simple regarding JSON.
Problem
I have a simple question regarding rendering JSON object from a Scala class. Why do I have to implemet deserializer ( read, write ). I have the following case class: ``` case class User(firstname:String, lastname:String, age:Int) ``` And in my controller: ``` val milo:User = new User("Sam","Fisher",23); Json.toJson(milo); ``` I get compilation error: No Json deserializer found for type models.User. Try to implement an implicit Writes or Format for this type. In my previous project I had to implement a reader,writer object in the class for it to work and I find it very annoying. ``` object UserWebsite { implicit object UserWebsiteReads extends Format[UserWebsite] { def reads(json: JsValue) = UserWebsite( (json \ "email").as[String], (json \ "url").as[String], (json \ "imageurl").as[String]) def writes(ts: UserWebsite) = JsObject(Seq( "email" -> JsString(ts.email), "url" -> JsString(ts.url), "imageurl" -> JsString(ts.imageurl))) } } ```