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)