下面的代码显示了我想要评估的示例JSON。
第2个断言声明有效,但其余的声明没有。 任何帮助都会很棒。
代码:
import groovy.json.*
def jsonText = '''
{
"message": {
"employees": [{
"firstName": "John",
"lastName": "Doe",
"age": 1
}, {
"firstName": "Anna",
"lastName": "Smith",
"age": 5
}, {
"firstName": "Peter",
"lastName": "Jones"
}],
"body": "Some message"
}
}
'''
def json = new JsonSlurper().parseText(jsonText)
def message= json.message
assert message.employees[0].age == 1
assert message.employees.size() == 3
// How to make the following tests work. Are there any options?
assert message.employees.age.size() == 2 // How many employees have an age key/value pair?
// What's the sum of the ages, if the value does not exist use 0
assert message.employees.sum { it.age==null?0:it.age } == 6 // Could I use some sort of null check?
assert message.employees.age.sum() == 6 // Is there a way to specify the default value
答案 0 :(得分:3)
首先,
// How many employees have an age key/value pair?
assert message.employees.findAll { it.age }.size() == 2
// Or
assert message.employees.age.findAll().size() == 2
总和:
// You could use the elvis operator
assert message.employees.sum { it.age ?: 0 } == 6