Code Monkeyism

Programming is hard by Stephan Schmidt

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.

@Path("/hello")
class HelloWorldResource {
  @GET
  @ProduceMime(Array("text/html"))
  def hello() = "Hello"

  @Path("/world")
  @GET
  @ProduceMime(Array("text/html"))
  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[_],
                typ:Type,
                annotations:Array[Annotation],
                mediaType:MediaType,
                stringObjectMultivaluedMap:MultivaluedMap[String,Object],
                outputStream:OutputStream):Unit = {
    val writer = new OutputStreamWriter(outputStream);
    writeTo(node, writer)
    writer.close()
  }

 [...]

  def isWriteable(dataType:java.lang.Class[_], typ:Type, annotations:Array[Annotation]) = {
    classOf[json.Node].isAssignableFrom(dataType);
  }

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.

About the author: Stephan Schmidt is currently a team manager at ImmobilienScout24 in Berlin. Stephan has been working as a head of development and CTO. He has used a lot of different technologies in the last 20 years including Java, Rails and Python. Stephans main field of interest is maintainablity and productivity in software development. Want to know more? All views are only his own.

If you did like this article but you don't want to subscribe to new articles with your reader, you can follow me on Twitter or subscribe to new posts with your email:

Comments

If you’re using the Scala Array class, then passing values into Java requires nothing more than a Java method which accepts a corresponding Java array. This works because Scala arrays are *literally* Java arrays, just with a little sugar built on top. The nice thing about this is you don’t have to worry about translation between languages, just pass values through.

Other collection types are a bit trickier, but the good news is that you don’t *really* need to convert anything, so long as you’re willing to call Scala APIs from Java (which works perfectly, it’s just not good ol’ java.util.List). Going the other direction is actually even easier (if that’s possible) since Scala includes wrappers for all of the Java Collections interfaces. These wrappers (in scala.collection.jcl) are automatically invoked (via implicit conversion) to wrap Java collections in more palatable Scala interfaces. Thus, while it is not possible to pass a java.util.List into a Scala method accepting Seq *from Java*, it should be fairly easy to just pass that same list into a Scala method which accepts that type, and then from there pass the list to the final target method (accepting Seq).

Stylistic note: any method which returns type Unit should be declared using the following special syntax. It’s not only shorter and more readable, but it can also prevent subtle mistakes when relying on type inference:

def doSomething() {
// do whatever I want
// return whatever I want…
// …because it’s thrown away
}

This is semantically identical to the following:

def doSomething(): Unit = {
// do whatever I want
// return whatever I want…
() // …because it’s thrown away
}

Obviously, the first one is nicer. :-)

stephan

Ah thanks.

Concerning the Unit syntax. As written before, I’m not sure type inference is always a good thing.

And especially as return types type declarations might be useful. Not to the compiler, but to the person who is reading a method.

val a = b.something()

is fine in my code

When someone wants to use something

def something():Int

might be easier to use than

def something()

Code is always written to be easily read and understood, not by optimizing the keys one needs to type.

Chekke

Stephan the first block of code it is Groovy or Scala? If is Scala it is a beauty to be a statically type language.

I should take a look more seriously to Scala.

stephan

@Chekke: Scala. Yes you should :-)

pstickne

I think the “def foo() {}” syntax is clear after it’s been used a few times. One issue that -has- bitten me a few times is the auto-coercion of any type to Unit. However, this would be the same even issue if I was using “def foo(): Unit = {}”.

Leave a Reply