Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to pretty-print a Scala case class to JSON in Play Framework 2.1.x?

I have a case class like

case class Person(firstName: String, lastName: String)

I'd like to pretty-print it as JSON. I am working within Play Framework 2.1.x. I also happen to have the Salat library in my classpath, so I could use that as well. I'd like to see what all the options are however including json4s, etc.

JSON libraries in Scala have been evolving rapidly. I believe this can be done with a few lines of code for all case classes (i.e. without requiring additional code for each case class) using macros and such.

I believe I can use play's built-in macro-based Json library, but I'd like to see some worked-out examples. I'm aware of a few starting points:

http://eng.42go.com/working-with-json-in-play-2-1/

https://github.com/novus/salat/wiki/JSON

Scala 2.10, its impact on JSON libraries and case class validation/creation

But I'd like to see examples using json4s and such as well.

like image 590
tksfz Avatar asked Dec 04 '25 14:12

tksfz


1 Answers

I like the built-in JSON support in Play 2.x. It works, it's well documented, and it's just one less dependency to worry about.

Your JSON pretty-print of Person would be accomplished in two lines (plus an import):

import play.api.libs.json._
...
implicit val personFormat = Json.format[Person]
println(Json.toJson(personToWrite))
like image 53
millhouse Avatar answered Dec 06 '25 03:12

millhouse