解析Json响应并检查Groovy中的缺失键

时间:2017-05-06 20:46:21

标签: json groovy

我想从下面的示例Json响应中读取值

"items": [
  {
    "kind": "books#volume",
    "id": "nwy8akU-nJUC",
    "volumeInfo": {
      "title": "Light In August",
      "authors": ["William Faulkner"],
      "publisher": "Random House",
      "publishedDate": "2013-07-05",
      "pageCount": 384,
      "categories": ["Fiction"]
    },
    "saleInfo": {
      "country": "IN",
      "saleability": "FOR_SALE",
      "isEbook": true,
      "listPrice": {
        "amount": 339.0,
        "currencyCode": "INR"
      }
    }
  }
]

当我读取响应并作为数组循环迭代时,数量和数量第二个结果中缺少currencyCode键,因此在数组中完全忽略了它。请帮助我如何遍历密钥并确定密钥是否不在那里然后设置值为null。

我写了一个下面的示例代码

testRunner.runTestStepByName("Volumes1")
def responseContent = context.testCase.getTestStepByName("Volumes1").getProperty("response").value
JsonSlurper jsonResponseContent = new JsonSlurper()
def jsonResponseObject = jsonResponseContent.parseText(responseText)
titleCount = jsonResponseObject.items.volumeInfo.title.size
arrayTitle = jsonResponseObject.items.volumeInfo.title
arrayAuthor = jsonResponseObject.items.volumeInfo.authors
arrayPublisher = jsonResponseObject.items.volumeInfo.publisher
arrayPublishDate = jsonResponseObject.items.volumeInfo.publishedDate
arrayPageCount = jsonResponseObject.items.volumeInfo.pageCount
arrayCategories = jsonResponseObject.items.volumeInfo.categories
arrayAmount = jsonResponseObject.items.saleInfo.listPrice.amount
arrayCurrencyCode = jsonResponseObject.items.saleInfo.listPrice.currencyCode    

0 个答案:

没有答案