简体   繁体   中英

Decoding Huge JSON Array URL using swift

I'm trying to decode data from this massive JSON Array https://coronavirus-19-api.herokuapp.com/countries I've had luck decoding by country or using the total stat worldwide https://coronavirus-19-api.herokuapp.com/all by doing the following

//
//  GlobalSwiftViewController.swift
//  Universal
//
//  Created by JOE on 3/20/20.


import UIKit

final class StatSwiftViewController: UIViewController {


   // THESE LABELS WILL RETRIEVE THE FOLLOWING DATA FROM THE URL: THE CASE , DEATH AND RECOVERED DATA
    @IBOutlet weak var CaseLable: UILabel! 

    @IBOutlet weak var DeathLable: UILabel!

    @IBOutlet weak var RecoveredLabel: UILabel!

    struct JSONTest: Decodable {
    let cases: Double
    let deaths: Float
    let recovered: Int?
}

    override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "https://coronavirus-19-api.herokuapp.com/all"
        guard let url = URL(string: urlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!.localizedDescription)
            }

            guard let data = data else { return }
            do {
                //Decode data
                let urlString = try JSONDecoder().decode(JSONTest.self, from: data)
                let numberFormatter = NumberFormatter()
                numberFormatter.numberStyle = .decimal

                //HERE WE ARE SHOWING TO THE USER THE DATA FROM THE URL ABOVE
                DispatchQueue.main.async {
                    self.CaseLable.text = numberFormatter.string(for: urlString.cases) 
                    self.DeathLable.text = numberFormatter.string(for: urlString.deaths)
                    self.RecoveredLabel.text = numberFormatter.string(for: urlString.recovered)

                    //self.timeLabel.text = JSONTest.deaths
                }

            } catch let jsonError {
                print(jsonError)
            }

            }.resume()
    }

}

Now I'm trying to decode all of the data in this URL https://coronavirus-19-api.herokuapp.com/countries to show in one view controller, I've had success by using the single URL https://coronavirus-19-api.herokuapp.com/countries/china for the country using the same code above by just adding more vars and labels However, I'm not able to add more counties by adding each URL for each country or using the main URL for all countries https://coronavirus-19-api.herokuapp.com/countries Therefore, H ow can I struct all Array List using the URL for all countries? note: Im trying to edit/update my code above to get the results as possible without installing extra pods or files...

Try to adapt your model to be able to decode the countries data.

You can test this in a Playground:

import Foundation

struct JSONTestElement: Codable {
    let country: String
    let cases, todayCases, deaths, todayDeaths: Int
    let recovered, active, critical, casesPerOneMillion: Int
}

typealias JSONTest = [JSONTestElement]

func decode() {

    let urlString = "https://coronavirus-19-api.herokuapp.com/countries"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        }

        guard let data = data else { return }

        do {
            //Decode data
            let countriesData = try JSONDecoder().decode(JSONTest.self, from: data)

            let china = countriesData.filter({ $0.country.contains("China")})

            print("China data: \(china)")

        } catch let jsonError {
             print(jsonError)
        }

     }.resume()
}

decode()

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