Creating Decode Path from JSON Data in Swift that Includes Numbers and Hyphens?

与世无争的帅哥 提交于 2021-01-29 09:32:13

问题


this is relatively new to me and I've searched high and low but have been unsuccessful in finding a similar scenario.

I have retrieved some JSON Data from an API URL and have successfully decoded and output various values from this data as strings by parsing the data to a separate sheet and using structs and constants with the 'Decodable' value set. The problem I have is that one of the containers in the Json data is a hyphenated date in this format dates['2020-11-04'] so swift will not let me create a struct with this name (also this looks like an array but there are no square brackets when viewing the unformatted JSON data in a web browser).

Here is the full path to the date I want to output as a string and the URL being used (copied from a web browser using JSON Viewer Pro):

dates['2020-11-04'].countries.Afghanistan.date

https://api.covid19tracking.narrativa.com/api/2020-11-04

Here is the sheet containing my Structs and constants to decode the data:

import Foundation

//I understand the below name will not work but i've included it to show my presumed process
struct CovidData: Decodable {
    let dates: dates[2020-11-04]
}

//Once again the below struct name does not work but i've included it as an example of my presumed process.
struct dates[2020-11-04]: Decodable {
    let countries: countries
}

struct countries: Decodable {
    let Afghanistan: Afghanistan
}
struct Afghanistan: Decodable {
    let date: String
}

Here is my management sheet with my API call and JSON Parse:

import Foundation

protocol CovidDataManagerDelegate {
    func didUpdateCovidData(_ covidDataManager: CovidDataManager, covid: CovidModel)
}

struct CovidDataManager {
    
    var delegate: CovidDataManagerDelegate?
    
    let covidURL = "https://api.covid19tracking.narrativa.com/api/2020-11-04"
    
    func getData() {
        let urlString  = covidURL
        performRequest(with:urlString)
        
    }
    
    func performRequest(with urlString: String){
        
        if let url = URL(string: urlString){
            
            let session = URLSession(configuration: .default)
            
            let task = session.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print("Error")
                    return
                }
                if let safeData = data {
                    if let covid = parseJSON(safeData){
                    self.delegate?.didUpdateCovidData(self, covid: covid)
                    }
                }
            }
            task.resume()
        }
        
        func parseJSON(_ covidData: Data) -> CovidModel?  {
            let decoder = JSONDecoder()
            do {
                let decodedData = try decoder.decode(CovidData.self, from: covidData)
                let date = decodedData.dates['2020-11-04'].countries.Afghanistan.date
                let covid = CovidModel(date: date)
                print(date)
                return covid
            } catch {
                print("Error with JSON Parse")
                return nil
            }
        }
    }

}

I have not included my UI update sheet as mentioned before the call and decode is working perfectly fine when decoding data with a JSON path made up entirely of strings it is only this container with additional symbols and numbers I am stumped with.

Hopefully I've supplied enough information and apologies if some of the terminology isn't accurate, this is still quite new to me.

Thanks!

来源:https://stackoverflow.com/questions/64714888/creating-decode-path-from-json-data-in-swift-that-includes-numbers-and-hyphens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!