Search code examples
groovyjsonbuilder

Groovy JsonBuilder call methods to add information


The following code works fine

def json = new JsonBuilder()

json {
  writeNumbers(delegate, "myNumbers")
}

println json.toPrettyString()

def writeNumbers(json, name) {
  json."$name" {
      "w" 32
      "h" 32
  }
}

But as soon as I move or add a writeNumbers call inside of another 'scope', I get a stackoverflow exception; just like so

def json = new JsonBuilder()

json {
  scopes {
    writeNumbers(delegate, "myNumbers")
  }
}

println json.toPrettyString()

def writeNumbers(json, name) {
  json."$name" {
      "w" 32
      "h" 32
  }
}

Result:

Caught: java.lang.StackOverflowError
java.lang.StackOverflowError

Why is this happening and how can I get around it? Thanks


Solution

  • I think this is caused by the underlying error that the method writeNumbers is unknown when building the chain of closures.

    You need to change:

    writeNumbers(delegate, "myNumbers")
    

    to

    this.writeNumbers(delegate, "myNumbers")
    

    And it will work... Interesting though, this feels like a bug... I'll investigate if I get some free time ;-)

    Edit: Found this previous question which shows the same thing