使用Swift 4和Xcode 9获取JSON数据 [英] getting JSON Data with Swift 4 and Xcode 9

查看:180
本文介绍了使用Swift 4和Xcode 9获取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用以下代码来获取我的JSON数据.它返回加载后错误".我在另一个应用程序中使用此JSON数据,并且可以正常工作.我正在尝试使用Swift 4来实现新的简化方法.代码的确可以达到打印语句下载"的地步.

I've been trying to work with the below code to get my JSON data. It returns "Error after loading". I am using this JSON data in another application and it works. I'm trying to implement the new simplified method using Swift 4. The code does work to the point of the print statement "downloaded".

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
    }
}

推荐答案

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

The problem is the missing property date in your Codable class. You need to set the decoder dateDecodingStrategy to .formatted and pass a fixed format dateFormatter. Btw I suggest changing your class for a struct, change your property names using the Swift naming convention camelCase and provide the custom 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()

这篇关于使用Swift 4和Xcode 9获取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆