尝试从JSON Swift中提取数据时出错

时间:2017-07-12 15:54:25

标签: ios json swift

因此,在尝试解析OpenWeatherApp API中的数据时,我在Xcode上遇到thread 4: SIGABRT错误。在控制台上出现的错误是:

  

无法转换类型' __ NSArrayM' (0x3419714)到' NSDictionary' (0x3419958)

我已经在这个论坛上看了不同的东西,似乎没有一个真正起作用。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var typeCity: UITextField!




var weatherDescription : String = ""
override func viewDidLoad() {
    super.viewDidLoad()

  //  let checkText = typeCity.text
   /*
    if typeCity?.text == nil{
        typeCity.placeholder = "Type a city with no spaces"
        let city = "Chicago"
    }
   */
   let city = "Chicago"

    /*
    if checkText != nil {
        typeCity?.text = city
    }
    */
          print("City: \(city)")

    // Do any additional setup after loading the view, typically from 
 a nib.
    let url = URL(string: 
 "http://api.openweathermap.org/data/2.5/weather?q=\
 (city)&appid=626a124ef0844d2e021329c38a5dfafd")
        let task = URLSession.shared.dataTask(with: url!) { (data, 
response, error) in
        if error != nil{
            print(error!)
        } else {
            if let urlContent = data {
                do {
                    let jsonResult = try 
 JSONSerialization.jsonObject(with: urlContent, options: 
JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(jsonResult)
                    //let lon = jsonResult["coord"]["lon"].double
                    //let lat  = jsonResult["coord"]["lon"].double
                    //let temp = jsonResult?["main"]["double"].double
                    //print


                    print(jsonResult["name"]!!)


                    let coordinates = jsonResult["coord"] as! [String:Any]//the coordinates parsing
                    print("Coordinates: \(coordinates)")
                    let lon = coordinates["lon"] as! Double
                    let lat = coordinates["lat"] as! Double
                    print("Latitude: \(lat) Longitude: \(lon)")

                    let main = jsonResult["main"] as! 
[String:Any]//for the temperature

                    let kelvin = main["temp"] as! Double
                    let degreesFahrenheit = 9/5 * (kelvin-273) + 32
                    print("Temperature: \(degreesFahrenheit)")
                    let humidity = main["humidity"] as! Double
                    let pressure = main["pressure"] as! Double
                    let temp_max = main["temp_max"] as! Double
                    let temp_min = main["temp_min"] as! Double

                    let description = jsonResult["weather"]
 ["description"]as! [String: Any]

                    print("description")


                } catch{
                    print("Json Processing has failed or city name not recognized.")
                }
               // let json = jsonResult(data: data)


                //print("Lat: \(String(describing: lat)) Lon: \
 (String(describing: lon)) Temp: \(String(describing: temp))")




            }
        }
    }
    task.resume()
}

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}}

以下行似乎有错误:

let description = jsonResult["weather"]["description"]as! [String: Any]

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您正尝试将数组隐式转换为字典。尝试安全地检查它的类型:

if let description = jsonResult["weather"]["description"] as? [String] {
    [...]
}