Skip to content

Instantly share code, notes, and snippets.

@zedar
Last active August 29, 2015 14:07
Show Gist options
  • Save zedar/79d87c3efc4913877021 to your computer and use it in GitHub Desktop.
Save zedar/79d87c3efc4913877021 to your computer and use it in GitHub Desktop.
Incompatibility of HTTPBuider and groovy.json.JsonOutput

Groovy - StackOverflowError while incompatible versions of HTTPBuilder and JsonOutput

When working on microservice API Gateway that is Ratpack based I encountered StackOverflowError thrown by groovy.json.JsonOutput.toJson() method.

Versions of groovyx.net.http.HTTPBuilder prior to 0.6 used internaly json-io library. As of version 0.6 it changed to native Groovy's JsonSlurper to cosume JSON.

If you use JsonOutput.toJson(groovyObject) and this groovyObject was generated by the following code:

def http = new HTTPBuilder(url)
def groovyObject = http.request(GET, JSON) { req ->
    response.success = { resp, json ->
        return json
    }
}

and then

JsonOutput.toJson(groovyObject)

you can expect to get StackOverflowError. Especially when http.request() returns JSON with attributes equal to null value. json-io internally converts nulls to JSONNul classes. What could bring circular dependency in JSON structure. JsonOutput does not handle circular dependency and its toJson() method throws stack overflow exception.

Please remember to define dependency for HTTPBuilder version grater than 0.6. Example gradle build file: build.groovy

dependencies {
    compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.2'
}

or with version of HTTPBuilder prior to 0.6 use json-io library to output JSON:

import com.cedarsoftware.util.io.JsonWriter

String jstr = JsonWriter.objectToJson(groovyObject)
jstr = JsonWriter.formatJson(jstr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment