【问题标题】:Groovy JsonBuilder array of objectsGroovy JsonBuilder 对象数组
【发布时间】:2015-03-10 20:45:42
【问题描述】:

我有一个遇到问题的 JsonBuilder。我希望输出如下所示:

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

我看到的是:

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

生成 JSON 文档的代码如下:

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]})
            }
        }
    }

【问题讨论】:

  • 我的回答能解决问题吗?
  • 是的 - 非常感谢!

标签: json groovy jsonbuilder


【解决方案1】:

需要同时迭代两个列表。试试:

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

完整示例:

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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 2016-07-11
    • 2012-06-13
    • 2014-09-06
    相关资源
    最近更新 更多