jsonstringgroovygstring

Confusing error when trying to create a JSON structure in Groovy


I am trying to create a JSON structure in groovy as such:

def builder = new JsonBuilder()

builder.configuration {
            software {
                name name
                version version
                description "description"
            }
            git {
                name "appName"
                repository "repo"
                branch "branch"
            }
        }

where name and version are GString implementations. But whilst the structure seems to get created fine according to the debugger, I am getting this error whenever I try to print it or write it to a file:

Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [*my actual value*]
Possible solutions: wait(), any(), wait(long), take(int), each(groovy.lang.Closure), tap(groovy.lang.Closure)

Changing name to a normal "String" by using quotation marks also gives the same error. What am I doing wrong?


Solution

  • It's because it thinks name(name) is a call to your variable called name which is a string in this case...

    You could call your variables names that are not in your json structure (ie: change the name string to be called nameValue or similar)

    Or you could use the map form of JsonBuilder:

    def builder = new JsonBuilder()
    
    def a = 'tim'
    def name = "$a"
    def version = "$a-1.0"
    
    def root = builder.configuration {
        software(
            name: name,
            version: version,
            description: "description"
        )
        git(
            name: 'appName',
            repository: 'repo',
            branch: 'branch'
        )
    }