Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework automatic JSON marshalling

I'm looking to be set straight on my understanding of how the Play Framework handles conversion of Scala objects to JSON and vice versa (specifically for RESTful APIs):

I've read over and over again across the web that using Play's JSON support is nothing but a pleasure. But coming from Spring where I have a built in HttpMessageConverter (specifically MappingJacksonHttpMessageConverter) which will auto marshall requests and responses in my controllers with hardly any effort.

Play, on the other hand, (it appears) requires you to write Read and Write converters for every class you intend to marshal. E.g. (from the Play Docs):

implicit val locationWrites: Writes[Location] = (
  (JsPath \ "lat").write[Double] and
  (JsPath \ "long").write[Double]
)(unlift(Location.unapply))

To me this seems tedious when compared to the built in automatic message converting capabilities of Spring. It is my understanding that Play also uses Jackson under the hood so can the same be accomplished with Scala / Play, or perhaps is my premise flawed?

like image 810
oym Avatar asked Dec 04 '25 01:12

oym


1 Answers

You can use the writes macro:

implicit val locationWrites = Json.writes[Location]

I've never used Spring, but according to the docs for MappingJacksonHttpMessageConverter, it will only work for typed beans and untyped HashMap instances. Play! has built in Writes instances for Scala Map instances, and the writes macro can easily create instances for case classes, so the functionality is similar. However, I would guess that case classes usually have less boilerplate than a typed bean, even with the extra line to create an implicit Writes instance.

like image 178
wingedsubmariner Avatar answered Dec 05 '25 14:12

wingedsubmariner