JSON datamapping using Groovy

Avisi werknemer

Avisi werknemer

Published: 10 June, 2014

Translating pieces of data to JSON is a common practice for most Java devs. When building for example a RESTful API you probably have a library like Jackson under the hood for doing POJO-to-JSON transformations and vice versa.

While this is great in a lot of cases - like building API's - there are times when POJO's don't really add anything. In these cases you wish to go straight to JSON. This could be the case when your data is already in a handy POJO-like format and you don't need a new set of POJO's solely for the purpose of outputting JSON. I encountered this during some integration work with Apache Camel.

Groovy Builders

Groovy features a number of builder classes to easily construct output such as XML, HTML and also JSON. Here's an example using Groovy's JsonBuilder. By using closures the data mapping becomes very clean, it almost feels like writing literal JSON even though you're writing Groovy.

import groovy.json.JsonBuilder
def record = request.body
def json = new JsonBuilder() json {
typenummer {
type record['type']
jaar record['jaar']
xyznummer record['xyz']
bestelnummer record['bestelingnummer']
}
afdeling record['instituut']
foobarnummer {
deel1 record['part1']
deel2 record['part2']
}
def results = []
for (i = 0; i < request.headers.numberOfXYZ; i++) {
def y = i // http://blog.freeside.co/post/46587122020/groovy-gotcha-for-loops-and-closure-scope
results.add({
bedrag request.body.get("/xyz/${y}/foobar")
valuta request.body.get("/xyz/${y}/barfoo")
})
}
resultaten(results)
code record['testcode']
omschrijving record['analyse']
detail record['materiaal']
aangevraagdDoor record['opdrachtgever']
} response = json.toString()

Performance

Besides the standard JsonBuilder Groovy also contains a StreamingJsonBuilder which works in almost the same way and is really handy when your JSON output becomes a bit bigger. Also Groovy 2.3 was released last month and ships with a completely new JSON parser/serializer (based on Boon) which claims to bring superior performance.

Java project

You don't have to go all-in on Groovy if you're working on a Java project. Using a bit of Groovy for data mapping is a valid use case. If for some reasons you can't use Groovy but still want to do a direct JSON mapping you might want to checkout one of the available Java fluent interfaces to construct your JSON output. For example the new javax.json API.

Did you enjoy reading?

Share this blog with your audience!