如何使用groovy声明json响应内容?

时间:2015-01-24 03:56:09

标签: groovy jsonslurper

在请求的回复中我有这个内容:

"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

请帮忙,谢谢

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:1)

它只是logoPosition,而不是logoPosition[0]

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