2

在响应请求时,我有以下内容:

"comp":[
{
"type":"header",
"version":1,
"settings":
     {"logo":"mylogo",
      "logoPosition":"left",
      "inverseLogosPosition":false,
      "headerTitle":"My Report",
      "headerTitlePosition":"left",
      "pageBreak":false
}
},

我想断言设置的内容。例如,我尝试这个来断言 logoPosition = "left"

断言 json.components.settings[0].logoPosition[0] == "left"

它不工作

这部分运行良好:

assert json.comp.type[0] == "header"
assert json.comp.version[0] == 1

请任何帮助,谢谢

4

2 回答 2

2

提供的 json 无效。您可以使用两种路径

assert slurped.comp.settings.logoPosition[0] == "left"
assert slurped.comp[0].settings.logoPosition == "left"

完整示例:

import groovy.json.JsonSlurper

def json = '''{
"comp":[
    {
        "type":"header",
        "version":1,
        "settings": {
            "logo":"mylogo",
            "logoPosition":"left",
            "inverseLogosPosition":false,    
            "headerTitle":"My Report",    
            "headerTitlePosition":"left",        
            "pageBreak":false
        }
    }
]}'''

def slurped = new JsonSlurper().parseText(json)

assert slurped.comp.settings.logoPosition[0] == "left"
assert slurped.comp[0].settings.logoPosition == "left"
于 2015-01-24T10:19:14.560 回答
1

只是logoPosition,不是logoPosition[0]

为什么不将一些预期的 json 作为字符串,用 JsonSlurper 将其转换为地图,然后比较这些?

于 2015-01-24T09:20:32.647 回答