如何使用变量从Groovy中提取JSON响应中的值?

时间:2016-10-12 23:09:39

标签: json groovy soapui assertion jsonslurper

我试图提取自行车品牌" Cannondale"从JSON响应中使用存储在名为" jsonFieldName"

的变量中的值的位置

或者,我可以使用以下语法成功提取品牌价值:

def response = ('''{
   "store": {
  "book": [
     {
        "title": "Sword of Honour",
        "category": "fiction",
        "author": "Evelyn Waugh",
        "@price": 12.99
     },
     {
        "title": "Moby Dick",
        "category": "fiction",
        "author": "Herman Melville",
        "isbn": "0-553-21311-3",
        "@price": 8.99
     },
     {
        "title": "Sayings of the Century",
        "category": "reference",
        "author": "Nigel Rees",
        "@price": 8.95
     },
     {
        "title": "The Lord of the Rings",
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "isbn": "0-395-19395-8",
        "@price": 22.99
     }
  ],
  "bicycle": {
     "brand": "Cannondale",
     "color": "red",
     "price": 19.95
  }
 }
}''').toString()

//store location of json property I want to extract in property called jsonFieldName
def jsonFieldName = "store.bicycle.brand"
def json = new JsonSlurper().parseText (response)
//perform extraction
brand = json."${jsonFieldName}"

但是,我想将元素的位置保存在变量中。原因是,我希望能够在Json Response上迭代多个断言,作为我的自动化套件的一部分。

有人可以建议怎么做吗?

以下是我目前在变量中存储位置的代码段。但它不起作用,总是将品牌归还为“Null' :( 感谢。

{{1}}

2 个答案:

答案 0 :(得分:3)

new JsonSlurper().parseText(response)会返回map,因此,搜索"store.bicycle.brand"会在store.bicycle.brand变量中查找名为json的密钥,而您希望查看首先在json['store']中,然后在索引['bicycle']中,依此类推。

我使用inject策略来做你想做的事:

def response = '''{
   "store": {
  "bicycle": {
     "brand": "Cannondale",
     "color": "red",
     "price": 19.95
  }
 }
}'''

def jsonFieldName = "store.bicycle.brand"
def json = new groovy.json.JsonSlurper().parseText (response)

get = { field, json2 ->
    field.tokenize(".").inject(json2) { map, f -> map[f] }
}

brand = get jsonFieldName, json
assert brand == 'Cannondale'

答案 1 :(得分:0)

问题是使用字符串访问属性;该字符串被视为属性的全名,因此您无法使用它来访问多个深度属性;换句话说,const QString getData();被视为属性名称的一部分。

可能的解决方法是将字符串拆分为.字符并逐个访问属性:

.
相关问题