在swift 4中获取json有什么问题?

时间:2017-10-07 18:04:27

标签: ios json swift swift4

我有一个天气预报JSON,我使用Swift 4中的新方法来序列化结构的JSON,但问题是当我想打印JSON时我会收到这个:

  

typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预计会解码数组,但会找到一个字典。”,underlyingError:nil))

这是我的JSON代码:

struct currently : Decodable {
let summary : String?
let temperature : Float?
let timezone : String

init(json : [String : Any]) {

    summary = json["summary"] as? String ?? ""
    temperature = json["temperature"] as? Float ?? -1
    timezone = json["timezone"] as? String ?? ""



}
}

以下是获取JSON的代码:

let jsonURL =  "https://api.darksky.net/forecast/[code]/\(ViewController.latitude),\(ViewController.longitude)"

    guard let url = URL(string : jsonURL) else {
        return
    }

    URLSession.shared.dataTask(with: url) { (data , response , error) in

        guard let data = data else {return}

        do {


            let currentlies =  try JSONDecoder().decode(currently.self , from : data)


            print(currentlies.timezone)
            print(currentlies.summary)
            print(currentlies.temperature)

        }

        catch {

            print(error)
        }
    }.resume()

1 个答案:

答案 0 :(得分:2)

您可以这样使用:

struct Response : Decodable {
    let timezone : String
    let currently: Currently
}

struct Currently: Decodable {
    let summary: String
    let temperature: Double
}

let jsonURL =  "https://api.darksky.net/forecast/[code]/\(ViewController.latitude),\(ViewController.longitude)"

guard let url = URL(string : jsonURL) else {
    return
}

URLSession.shared.dataTask(with: url) { (data , response , error) in
   guard let data = data else {return}
    do {
        let currentlies =  try JSONDecoder().decode(Response.self , from : data)

        print(currentlies.timezone)
        print(currentlies.currently.summary)
        print(currentlies.currently.temperature)
    } catch {
        print(error)
    }
}.resume()