簡體   English   中英

Swift 4 JSON解碼

[英]Swift 4 JSON decoding

我正在嘗試解碼JSON。 我用於解碼JSON的快捷功能是:

func GetChapInfo(){

    let endpoint = "https://chapel-logs.herokuapp.com/chapel"

    let endpointUrl = URL(string: endpoint)

    do {
        var request = URLRequest(url: endpointUrl!)
        request.httpMethod = "GET"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = URLSession.shared.dataTask(with: request){
            (data: Data?, response: URLResponse?, error: Error?) in


            let dataAsString = String(data: data!, encoding: .utf8)
            //print(dataAsString)

            if(error != nil) {
                print("Error")
            }
            else{
                do{
                    guard let chapData = try? JSONDecoder().decode(Chapel.self, from: data!) else {
                        print("Error: Couldn't decode data into chapData")
                        return
                    }
                    for E in chapData.chap {
                        print(E.Day as Any)
                    }
                }
        }
        }

        task.resume()
    }
}

我在Swift中的struct

struct Chapel: Decodable {
    let chap: [Chap]
}

struct Chap: Decodable {
    let Name: String?
    let Loc: String?
    let Year: Int?
    let Month: Int?
    let Day: Int?
    let Hour: Int?
    let Min: Int?
    let Sec: Int?
}

我從服務器得到的響應是:

{"chap":{"Name":"Why Chapel","Loc":"FEC","Year":2018,"Month":9,"Day":4,"Hour":16,"Min":1,"Sec":7}}

但是,當我運行此程序時,程序將打印出“錯誤:無法將數據解碼為chapData”,我無法弄清楚原因。

首先catch解碼錯誤。 從不try? 捕獲的錯誤更具描述性

預期對Array<Any>進行解碼,但找到了字典

裝置:用於鍵的值chap是一個字典,不是數組

struct Chapel: Decodable {
    let chap: Chap
}

然后你必須打印

print(chapData.chap.Day) 

您可以減少代碼。 不需要顯式的URLRequest和默認GET請求的標頭。 這足夠了:

let endpoint = "https://chapel-logs.herokuapp.com/chapel"
let endpointUrl = URL(string: endpoint)!

do {

    let task = URLSession.shared.dataTask(with: endpointUrl) { (data, response, error) in
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM