使用Swift 4和Xcode 9获取JSON数据

时间:2017-12-07 22:33:27

标签: json swift

我一直在尝试使用以下代码来获取我的JSON数据。它返回“加载后出错”。我在另一个应用程序中使用此JSON数据,它的工作原理。我正在尝试使用Swift 4实现新的简化方法。代码确实起到了“下载”的打印语句的作用。

class MortgageRatesVC: UIViewController {
    final let url = URL (string:"http://mortgous.com/JSON/currentRatesJSON.php")

    override func viewDidLoad() {
        super.viewDidLoad()

        downloadJason()
    }

    func downloadJason () {
        guard let downloadURL = url else { return }
        URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
            guard let data = data, error == nil, urlResponse != nil else {
                print("Oops Call for Help")
                return
            }

            print("downloaded")
            do
            {
                let decoder = JSONDecoder()
                let rates = try decoder.decode([LenederRates].self, from: data)
                print(rates)
            } catch {
                print("Error after loading")
            }
        }.resume()
    }
}

class LenederRates: Codable {
    let key : String
    let financial_institution : String
    let variable_rate : String
    let six_months : String
    let one_year : String
    let two_year : String
    let three_year : String
    let four_year : String
    let five_year : String
    //  let date : Date

    init(key: String, financial_institution: String, variable_rate: String, six_months: String, one_year: String, two_year: String, three_year: String, four_year: String, five_year: String) {
        self.key = key
        self.financial_institution = financial_institution
        self.variable_rate = variable_rate
        self.six_months = six_months
        self.one_year = one_year
        self.two_year = two_year
        self.three_year = three_year
        self.four_year = four_year
        self.five_year = five_year
    }
}

1 个答案:

答案 0 :(得分:0)

问题是Codable课程中缺少属性日期。您需要将解码器dateDecodingStrategy设置为.formatted并传递固定格式的dateFormatter。顺便说一下,我建议更改结构的类,使用Swift命名约定camelCase更改属性名称并提供自定义CodingKeys:

struct LenederRates: Codable {
    let key: String
    let financialInstitution : String
    let variableRate: String
    let sixMonths: String
    let oneYear: String
    let twoYear: String
    let threeYear: String
    let fourYear: String
    let fiveYear: String
    let date: Date
    private enum CodingKeys: String, CodingKey {
        case key, financialInstitution = "financial_institution", variableRate = "variable_rate", sixMonths = "six_months", oneYear = "one_year", twoYear = "two_year", threeYear = "three_year", fourYear = "four_year", fiveYear = "five_year", date
    }
}
let mortgousURL = URL(string:"http://mortgous.com/JSON/currentRatesJSON.php")!
URLSession.shared.dataTask(with: mortgousURL) { data, urlResponse, error in
    guard let data = data else { return }
    do {
        let dateFormat = DateFormatter()
        dateFormat.locale = Locale(identifier: "en_US_POSIX")
        dateFormat.dateFormat = "yyyy-MM-dd"
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .formatted(dateFormat)
        let rates = try decoder.decode([LenederRates].self, from: data)
        print(rates)
    } catch {
        print(error)
    }
}.resume()