如何在swift中访问json对象里面的数组

时间:2016-11-07 10:13:26

标签: ios arrays swift dictionary swift3

无法访问json对象,这是json对象中的数组 我想从json对象访问数据,其中数组内有数组 并且还上传了json文件 所以任何人都可以检查并帮助我如何获得" weather.description"  数据

 override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!

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

        if error != nil {
            print("some error occured")
        } else {

            if let urlContent =  data {

                do{
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                    let newValue = jsonResult as! NSDictionary

                    print(jsonResult)

                    let name = newValue["name"]
                    //Here i am getting name as variable value

                    //this is not working
                    let description = newValue["weather"]??[0]["description"]

                    //this is not working
                    let description = newValue["weather"]!![0]["description"]

                    print()

                }catch {
                    print("JSON Preocessing failed")
                }

            }
        }
    }
    task.resume()

}

can anyone help me to get that data from weather.description

1 个答案:

答案 0 :(得分:1)

我已编辑了一些代码,并添加了一些注释。基本上,让我们检查您的响应结构的类型,并获得所需的值。

let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print("some error occured")
            } else {

                if let urlContent =  data {

                    do{
                        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                        // I would not recommend to use NSDictionary, try using Swift types instead
                        guard let newValue = jsonResult as? [String: Any] else {
                            print("invalid format")
                            return
                        }

                        // Check for the weather parameter as an array of dictionaries and than excess the first array's description
                        if let weather = newValue["weather"] as? [[String: Any]], let description = weather.first?["description"] as? String {
                            print(description)
                        } 

                    }catch {
                        print("JSON Preocessing failed")
                    }
                }
            }
        }
        task.resume()