简体   繁体   中英

Json parsing Swift not getting print

I am new to Swift. I want to fetch some json data from the server using the url. I tried many other solutions but they didn't work. I want to print the duration key (text and value) from the array and then print it in console.

The Json data is attached below

{
    "status": "OK",
    "rows": [
        {
            "elements": [
                {
                    "duration": {
                        "text": "3 hours 49 mins",
                        "value": 13725
                    },
                    "distance": {
                        "text": "225 mi",
                        "value": 361715
                    },
                    "status": "OK"
                }
            ]
        }
    ],
    "origin_addresses": [
        "Washington, DC, USA"
    ],
    "destination_addresses": [
        "New York, NY, USA"
    ]
}

Attached Code

func getdatajson1(){
        
        if let url = URL(string: "http://www.json-generator.com/api/json/get/bQywstyfkO?indent=2") {
            URLSession.shared.dataTask(with: url) { data, response, error in
                if let data = data {
                    do {
                        let res = try JSONDecoder().decode(Root.self, from: data)
                        print(res.rows)
                    } catch let error {
                        print(error)
                    }
                }
                }.resume()
        }
        
    } 



 struct Root: Codable {
        let rows: [Root2]
    }
    
    
    struct Root2: Codable {
        let elements: [Root3]
    }
    
    struct Root3: Codable {
        let elements: [node]
    }

    
    
    struct node: Codable {
        let duration : [valuesarray]
    
    }
    
    struct valuesarray: Codable {
        let text : String 
        let value : Int
    }

The duration is an Object and not an Array , also change your names and you can use this:

struct Root: Decodable {

  let rows: [Rows]

}

struct Rows: Decodable {

 let elements: [Elements]

}

struct Elements: Decodable {

  let duration, distance: LocationValues
}

struct LocationValues: Decodable {
   let text: String
   let value: Int
}

func getdatajson1(){

        if let url = URL(string: "http://www.json-generator.com/api/json/get/bQywstyfkO?indent=2") {
            URLSession.shared.dataTask(with: url) { data, response, error in
                if let data = data {
                    do {
                        let res = try JSONDecoder().decode(Root.self, from: data)
                        if let row = res.rows.first, let elements = row.elements.first {
                            print(elements.duration.text) //This is how you can get the text value
                            print(elements.distance.text) //This will print the distance
                        }

                    } catch let error {
                        print(error)
                    }
                }
                }.resume()
        }

    } 

Replace your codable struct with the below

class Result: Codable {
    var status:String?
    var rows:[Row]?
    var origin_addresses:[String]?
    var destination_addresses:[String]?
}

class Row: Codable {
    var elements:[Element]?
}

class Element: Codable {
    var status:String?
    var duration:Duration?
    var distance:Distance?
}

class Duration: Codable {
    var text:String?
    var value:Int?
}

class Distance: Codable {
    var text:String?
    var value:Int?
}

You should update your node model like below

struct node: Codable {
     let duration : valuesarray
     let distance : valuesarray
     let status : String
}

And you can access your duration data from API response like below

if let rows = res.rows, rows.count > 0 {

      //Access the element objects from rows
      let arrElements = rows[0].elements, arrElements.count > 0 {

          if let durationData = arrElements[0].duration { //get your duration object
               print(durationData.text)
               print(durationData.value)
          }
      }
}

try this:

and a hint: go to https://app.quicktype.io/ -> here you can paste your json and you will get your datastructs for free! ;)

func getdatajson1(){

            if let url = URL(string: "http://www.json-generator.com/api/json/get/bQywstyfkO?indent=2") {
                URLSession.shared.dataTask(with: url) { data, response, error in
                    if let data = data {
                        do {

                            let res = try JSONDecoder().decode(Welcome.self, from: data)
                            print(res.rows)
                        } catch let error {
                            print(error)
                        }
                    }
                }.resume()
            }

        }

        getdatajson1()


       struct Welcome: Codable {
            let status: String
            let rows: [Row]
            let originAddresses, destinationAddresses: [String]

            enum CodingKeys: String, CodingKey {
                case status, rows
                case originAddresses = "origin_addresses"
                case destinationAddresses = "destination_addresses"
            }
        }

        // MARK: - Row
        struct Row: Codable {
            let elements: [Element]
        }

        // MARK: - Element
        struct Element: Codable {
            let duration, distance: Distance
            let status: String
        }

        // MARK: - Distance
        struct Distance: Codable {
            let text: String
            let value: Int
        }

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