[英]Groovy JsonBuilder array of objects
I have a JsonBuilder that I'm having some trouble with. 我有一个遇到问题的JsonBuilder。 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: 生成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]})
}
}
}
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.