2016-11-07 61 views
-2

JSON对象数组内无法访问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

+0

您使用的是什么Swift版本? 3.0? – dirtydanee

+0

让我们一块一块地做。 'let weatherValue = newValue [“weather”]'returns?如果它返回正确,'let firstWeather = weatherValue [0]'返回?如果返回正确,'let weatherDescription = firstWeather [“description”]'返回? – Larme

+0

其不起作用 其给出错误 “类型”任何?有没有下成员” 是可能的,因为我正在转换结果为NSDictionary的 因为我想大多数的选项和它不工作,并给这个错误 –

回答

1

我编辑了自己的代码位,并增加了一些注解。 Basiclly,让我们检查你的响应结构的类型,并获得所需的值。

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() 
+0

它的工作还有一件事u能告诉我为什么u使用此语法 [[String:Any]] 和为什么我不应该使用NSDictionary –

+1

'Dictionary'([String:Any])是一个本地的Swift结构。 'NSDictionary'是一个Cocoa类。如果您使用Swift,请尝试使用本机Swift语言元素!顺便说一句,如果它的工作,将其标记为接受答案请。 – dirtydanee

+0

我可以有你的电子邮件地址或Twitter的详细信息 –