Search code examples
jsongroovyjsonbuilder

Groovy JsonBuilder array of objects


I have a JsonBuilder that I'm having some trouble with. I'd like the output to look like the following:

"unitTests": {
        "testType": "TestNG",
        "totalTests": 20,
        "failedTests": 2,
        "skippedTests": 0,
        "failedTestList": [
            {
                "class": "SomeTestClass"
                "method": "someTestMethod"
            },
            {
                "class": "AnotherTestClass"
                "method": "anotherTestMethod"
            }
        ]
    }

Instead what I am seeing is:

"unitTests": {
        "testType": "TestNG",
        "totalTests": 20,
        "failedTests": 2,
        "skippedTests": 0,
        "failedTestList": [
            [
                {
                    "class": "SomeTestClass"
                }
            ],
            [
                {
                    "method": "someTestMethod"
                }
            ],
            [
                {
                    "class": "AnotherTestClass"
                }
            ],
            [
                {
                    "method": "anotherTestMethod"
                }
            ]
        ]
    }

The code to generate the JSON document is below:

def json = new JsonBuilder()

    def root = json {
        time { $date timestamp }
        data {
            unitTests {
                testType unitType
                totalTests totalUnitTests
                failedTests failedUnitTests
                skippedTests skippedUnitTests
                failedTestList(failedUnitTestClass.collect {[class: it]}, failedUnitTestMethod.collect {[method: it]})
            }
        }
    }

Solution

  • There's a need to iterate both lists at the same time. Try:

    [failedUnitTestClass, failedUnitTestMethod].transpose().collect { [class:it[0], method:it[1]] }
    

    Full example:

    import groovy.json.*
    
    def json = new JsonBuilder()
    def failedUnitTestClass = ['cls1', 'cls2', ]
    def failedUnitTestMethod = ['m1', 'm2', ]
    
    json.unitTests {
        failedTestList([failedUnitTestClass, failedUnitTestMethod].transpose().collect {[class:it[0], method:it[1]]})
    }
    println JsonOutput.prettyPrint(json.toString())