JsonBuilder for Scala, REST and Jersey

How to generate Json for REST? If you're suspicious of automatic generation like me?* I've created a markup builder which can be used with Json and made a look into the future in my post "The best Markup Builder I could build in Java":

"Closures in Java 7 will make it much easier to write a MarkupBuilder. The Action and Loop inner classes will go away and the code will be more Groovy like."

* For a discussion on why you might not want to use JAXB and XStream see the comments on "REST: Lean JSON and XML from the same code"

Let's have a look at this quote again. I didn't use Groovy but with some interest in Scala - because it might be more maintainable than Java after 5-years project life time as it is more concise but not riddled with the Ruby-problems or unreadable for most as Haskell is - I looked at my JsonBuilder code and tried it with Scala.

I went back to the "Experiments to nicely generation JSON" post and did adapt it to Scala.

class HelloWorldResource {
  def hello() = "Hello"

  def helloWorld = $( 
      $("id", 128),
      $("name", "stephan"),
      $("roles", roles.map(r => $("name", r.name))),
      $("adress", $(
        $("street", "mine!"),
        $("city", "Berlin")

The generating code looks the same as in Java, with the possibility to include functions for generating nodes. My Java code did need anonymous inner classes to achieve the same - with more noise and less power. The methods are shorter and the focus lies more on generating the JSON data, not the method boilerplate code. Next will be WebBeans or Guice integration.

Ive struggled with some Scala constructs, the JsonAdapter which implements MessageBodyWriter was a little hard to write, especially:

   def writeTo(node:Node, aClass:java.lang.Class[_], 
                outputStream:OutputStream):Unit = {
    val writer = new OutputStreamWriter(outputStream);
    writeTo(node, writer)


  def isWriteable(dataType:java.lang.Class[_], typ:Type, annotations:Array[Annotation]) = {

But everything works now and I can move on to adapt and learn how to do it better in Scala.

The migration wasn't that hard, some problems exists and my Scala code looks more like Java than Scala, but it's a beginning. One of my fears is to translate between Seqs, Lists, Arrays and Java Lists and Iterators all the time when interfacing with Java libraries. Not sure yet how to fix that, perhaps with some wrappers. Scalaz might help too. We'll see in my future adventures into Scala.

Thanks for listening.

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me