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.
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. :-)
September 18th, 2008