Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Scala pickling is the new, up and coming way to do this. It should be really fast and looks quite simple.

Current version is 0.8.0-SNAPSHOT and future 0.8.0 is advertised to be a stable release.

You need more dependencies to handle JSON:

libraryDependencies += "com.typesafe.play" %% "play-json" % "2.7.0"    

Then you can import new libs and use the produced JSON:

import play.api.libs.json.Json
val readableString: String = Json.prettyPrint(json)

The latter line is just an example, usually you don't use it this way directly, but use it to save or exchange data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top