Grails, jackson, json technologies

Speedup of JSON parsing in Grails

Optimizing Web application request processing time is an important stage of quality product development. While doing this part of the work on one of our products we noticed that the huge bottleneck was buried inside built-in JSON support in Grails. The problem was that built-in JSON parser that comes with Grails is surprisingly slow. Thats why we considered switching to using Java-based JSON parser instead.

Jackson is considered to be one of the fastest (if not the fastest) Java-based parsers. To use it inside grails project one should do the following:

Add the jackson dependencies into BuildConfig.grooovy file:

1
2
3
4
5
dependencies {
    compile 'org.codehaus.jackson:jackson-core-asl:1.8.3'
    compile 'org.codehaus.jackson:jackson-mapper-asl:1.8.3'
   // ...
}

Parsing JSON objects using Jackson is very similar to the build-in grails parser, for example to parse the array of JSON objects one should use the code like that using built-in grails parser:

1
2
3
4
5
6
7
String jsonString = ...
JSONArray array = JSON.parse(jsonString)
for (int i = 0; i < array.size(); i++) {
    JSONObject map = array.getJSONObject(i)
    println map
    // The JSON object is parsed using grails into usual property -> value map
}

To do the same using Jackson you should write the following code:

1
2
3
4
5
6
7
String jsonString = ...
ObjectMapper mapper = new ObjectMapper()
List<Object> array = mapper.readValue(jsonString, List.class)
for (Map map : array) {
    println map
    // The JSON object is parsed using Jackson into usual property -> value map
}

Writing JSON is also simple using Jackson:

1
2
3
Map jsonObject = ...
ObjectMapper mapper = new ObjectMapper()
String jsonString = mapper.writeValueAsString(jsonObject)

As a result of switching to Jackson to parse and write JSON we've got 10x time improvement of our request processing latency.

Looking to hire a software developer?
Don't hesitate to contact us.

Comments