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:
dependencies {
compile 'org.codehaus.jackson:jackson-core-asl:1.8.3'
compile 'org.codehaus.jackson:jackson-mapper-asl:1.8.3'
// ...
}
Code language: JavaScript (javascript)
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:
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
}
Code language: PHP (php)
To do the same using Jackson you should write the following code:
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
}
Code language: JavaScript (javascript)
Writing JSON is also simple using Jackson:
Map jsonObject = ...
ObjectMapper mapper = new ObjectMapper()
String jsonString = mapper.writeValueAsString(jsonObject)
Code language: JavaScript (javascript)
As a result of switching to Jackson to parse and write JSON we’ve got 10x time improvement of our request processing latency.