快速解析JSON失败

时间:2018-07-01 16:11:05

标签: json swift codable

我确认内容没有错。当我只解析一次时,它与nil相同。

struct MyFriend: Codable {

var id: String
var friendName: String
var latitude: String
var longitude: String
var lastUpdateDateTime: String

enum CodingKeys: String, CodingKey {
    case id = "id"
    case friendName = "friendName"
    case latitude = "lat"
    case longitude = "lon"
    case lastUpdateDateTime = "lastUpdateDateTime"
}

}

这是我的解析过程

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    let task = session.dataTask(with: targetURL) { (data, respnse, error) in

        if let error = error {
            print("Donwnload Fail: \(error)")
            return
        }

        guard let data = data else {
            print("Data is nil")
            return
        }

        // Parse JSON from data
        let decoder = JSONDecoder()
        let results = try? decoder.decode([MyFriend].self, from: data)

        if let results = results {
            print("results: \(results)")
        } else {
            // Pares Fail
            print("Pares Fail")
        }

    }

    task.resume()
}

URL中没有错误。我不知道为什么解析总是会失败。

0 个答案:

没有答案