简体   繁体   中英

Parse Json response and check missing key in Groovy

I want to read the values from below sample Json response

"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"
      }
    }
  }
]

When I read the response and iterate in a loop as an array, amount & currencyCode keys are missing in the second result thus its totally ignored in the array. Please help me as to how to loop through the key and identify if the key is not there then set value null.

I have written a below sample code

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    

Try:

arrayAmount = jsonResponseObject.items.saleInfo?.listPrice?.amount
arrayCurrencyCode = jsonResponseObject.items.saleInfo?.listPrice?.currencyCode 

println "list price amount : ${arrayAmount}"
println "list price currency code : ${arrayCurrencyCode}"

The above uses null safe. Refer here for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM