0

我正在尝试解码 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()
    }
}

struct在 Swift 中是

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”,我无法弄清楚原因。

4

1 回答 1

2

首先是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
    ...
于 2018-09-04T17:13:17.787 回答