How to get parsed JSON back from api?

Viewed 65

This is my first time attempting to parse JSON from an api. I try to print the JSON but nothing is in the console. I am trying to get zipcodes in a radius from me.

This is how the JSON looks on the api's websiteimage of website

My codable structs:

struct Zip: Codable {
    let Distance: Int
    let City: String
    let County: String
    let StateAbbr: String
    let ZipCode: String
}
struct Zips: Codable{
    var results: [Zip]
}

viewDidLoad

    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        let urlString = "https://zipcodedownload.com/Radius?firstzipcode=30316&radiuscoverage=10&format=json&pagenumber=1&key=9e2b15aa17f9434cbe62ddc32b40a521"
        let url = URL(string: urlString)
        guard url != nil else {
            return
        }
        let session = URLSession.shared
        let dataTask = session.dataTask(with: url!) { (data, response, error) in
            if error == nil && data != nil{
                let decoder = JSONDecoder()
                do{
               let resultsZips = try decoder.decode(Zips.self, from: data!)
                    print(resultsZips)
                }
                catch{
                     print(error)
                }
            }
        }
        dataTask.resume()
    }

Can someone point me in the right direction or tell me what I am doing wrong?

1 Answers
  1. You are fetching an array of Zip (not a results key containing them). So first, you need to change the decoder:
decoder.decode([Zip].self, from: data!)
  1. Sometimes Distance is not rounded. So you need to change its type to Double.

  2. You will get the answer now but you should read the documentation of your API first, maybe some of them are optionals or maybe something else ‍♂️

Related