Categories

Scala JSON Generator

I am working with Scala more and more at the moment. I find it a really powerful and fun language to work in. One of the recent tasks has been to translate various tab delimited data files into a common JSON format. In java land, I’ve used Jackson to great effect, but it really doesn’t feel very Scala. My colleague and I were busy following the Jackson route and had a working implementation, but it just didn’t feel clean, simple and Scala idiomatic. That’s when we decided to define how we thought the api should work.

One of the great things about using Scala, is it’s a fantastic language for creating DSLs. When I really don’t like the way the code that solves a specific problem looks, I like to write the pseudo code that feels right, and then figure out how to make that work. With Scala, I have had a great deal of success in this approach. We started off defining a JSON generator DSL that looked like this:-

  1. def mapToJson(myMap: Map[String, String]) = {
  2.   val json = jsonObject {
  3.     field("cheese", myMap.get("name")
  4.     jsonObject("Score") {
  5.       field("aroma", myMap.get("smell")
  6.       field("flavor", myMap.get("taste")
  7.       field("texture", myMap.get("squidginess")
  8.     }
  9.     jsonArray("servedOn") {
  10.       jsonObject {
  11.         field("cracker", myMap.get("crackerType")
  12.         field("maker", myMap.get("crackerMaker")
  13.       }
  14.     }
  15.     jsonArray("sampledOn") {
  16.       value(myMap.get("firstTried")
  17.       value(myMap.get("secondTried")
  18.       value(myMap.get("thirdTried")
  19.     }
  20. }

There was another case for jsonArray, which doesn’t involve having a field name, i.e. jsonArray { … }. Whilst attempting to find a way to implement the DSL that would satisfy this, we had to make a small compromise. The call jsonObject {…} and jsonObject(“fieldName”) {…} caused problems because the signatures of the DSL methods were indistinguishable when using them. The compromise we struck on was jsonObject() {…} and jsonObject(“fieldName”) {…}, i.e. just adding the empty parenthesis. This then is the resulting syntax, and the implementation can be found here.

This is a first cut, but as this library was introduced to solve a problem in our production app. It will be tweaked and maintained so any bugs or extra features will quickly get incorporated.

4 comments to Scala JSON Generator

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>