the blog for developers

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.

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.
Leave a reply.

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

What people wrote somewhere else:

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?