简体   繁体   中英

Trouble reading json output using groovy

I have a json output that I have been able to parse successfully but I'm not able to read some of the properties value using groovy

From the below json data, I can parse this data

def parsedJsonGet = new groovy.json.JsonSlurper().parseText(Response)
def i = -1
parsedJsonGet.each {
thisRecord ->
i= i+1
//Here using thisRecord can go through each node
}

From the below json data I would like to read say Street value of each such nodes.

Json Code is in this format:

{
    [
        "Name": "ABC",
        "Address": {
            "":0,
            "City": [
                {
                "Street": "Data1",
                "Apt": "Data2",
                "Pin": "Data3",
                }
            ]
        }
},
{
    [
        "Name": "ABC",
        "Address": {
            "":0,
            "City": [
                {
                "Street": "",
                "Apt": "",
                "Pin": "",
                }
            ]
        }
}   

Making a few assumptions about your payload, which isn't well-formed JSON, you could parse the data this way:

def Response = '''{
  "Records": [
    {
      "Name": "ABC",
      "Address": {
        "Number": 0,
        "City": [
          {
            "Street": "Data1",
            "Apt": "Data2",
            "Pin": "Data3"
          }
        ]
      }
    }
  ]
} '''

def parsedJsonGet = new groovy.json.JsonSlurper().parseText(Response)

parsedJsonGet.Records.each {
   thisRecord -> System.out.println('Street is ' + thisRecord.Address.City[0].Street)
}

Because City is an array, I'm assuming you want just the first City/Street record. This will return: This record is Data1

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