2016-11-07 66 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的詳細信息 –