我似乎无法访问 swiftyJSON 中的子数组

I can't seem to access sub arrays in swiftyJSON

所以这里是 JSON

{
"city": {
"id": 4930956,
"name": "Boston",
"coord": {
  "lon": -71.059769,
  "lat": 42.358429
},
"country": "US",
"population": 0,
"sys": {
  "population": 0
}
},
"cod": "200",
"message": 0.0424,
"cnt": 39,
"list": [
{
  "dt": 1473476400,
  "main": {
    "temp": 76.33,
    "temp_min": 73.11,
    "temp_max": 76.33,
    "pressure": 1026.47,
    "sea_level": 1027.96,
    "grnd_level": 1026.47,
    "humidity": 73,
    "temp_kf": 1.79
  },
  "weather": [
    {
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10n"
    }
  ],
  "clouds": {
    "all": 8
  },
  "wind": {
    "speed": 7.29,
    "deg": 300.501
  },

这里是我的控制器,我去那里抓取数据......

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var amConnected: UILabel!

@IBOutlet weak var weatherTable: UITableView!
var arrRes = [[String:AnyObject]]()
var swiftyJsonVar: JSON?

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.doSomethingNotification(_:)), name: "ReachabilityChangedNotification", object: nil)

    let openWMAPI = "http://api.openweathermap.org/data/2.5/forecast/city?q=Boston,Ma&APPID=XXXXXXXXXXXXXXX&units=imperial"

    Alamofire.request(.GET,openWMAPI).responseJSON{
        (responseData) -> Void in
        print(responseData)
        let swiftyJsonVar = JSON(responseData.result.value!)

               self.weatherTable.reloadData()

        }
        .responseString{ response in
            //print(response.data.value)
           // print(response.result.value)
            //print(response.result.error)
            //eprint("inhere");

    }

    weatherTable.rowHeight = UITableViewAutomaticDimension
    weatherTable.estimatedRowHeight = 140
    // Do any additional setup after loading the view, typically from a nib.
}

在我的 table 循环中,它现在说 jsonArray 为 nil 并且失败了。 我不确定我现在做错了什么。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = weatherTable.dequeueReusableCellWithIdentifier("theCell", forIndexPath: indexPath)
    let label1 = cell.viewWithTag(101) as! UILabel
    print("inhere")


    if((swiftyJsonVar) != nil){
    if let jsonArray = self.swiftyJsonVar["list"].array {
        var temp = jsonArray[indexPath.row]["main"]["temp"].float
        var rdate = jsonArray[indexPath.row]["dt_txt"].string
        print(temp)
    }else{
        print("test")
    }
    }


    label1.text = "TEST"

    return cell
}

总的来说,我只是不确定如何深入 JSON 的下一个级别。

如果您不反对,请尝试使用 AlamofireObjectMapper 而不是 SwiftyJson

1) 如果您要经常更改 json 键的名称,并且要进行大量枚举转换,请尝试:

AlamofireObjectMapper

2) 如果名称要相同,只需进行最少的转换,直接使用: AlamofireJsonToObjects

这两种情况,都为您的 json 对象创建模型 classes。如果你有一个数组——你可以将一个 var 定义为一个数组 如果它是一个对象或一个对象数组 - 然后您可以创建另一个模型 class ,它再次是可映射的,然后在原始模型中定义这样一个对象 var。

上述库将使您的代码在将对象提取到 json 时非常干净。

您可以使用连续下标访问 SwiftyJSON 中 JSON 数组中的元素,如果我们有以下 JSON 例如:

var json: JSON =  ["name": "Jack", "age": 25, 
                   "list": ["a", "b", "c", ["what": "this"]]]

然后就可以访问主数组中包含的子数组list的四个元素,例如:

json["list"][3]["what"] // this

或者你可以像这样定义一个路径let path = ["list",3,"what"]然后这样调用它:

json[path] // this

有了上面的解释,让我们用你的 JSON 文件来介绍它来列出数组中的元素 weather:

if let jsonArray = json["list"].array {

   // get the weather array
   if let weatherArray = jsonArray[0]["weather"].array {

       // iterate over the elements of the weather array
       for index in 0..<weatherArray.count {

           // and then access to the elements inside the weather array using optional getters.
           if let id = weatherArray[index]["id"].int, let main = weatherArray[index]["main"].string {
                print("Id: \(id)")
                print("Main: \(main)")
           }
       }
   }
}

您应该会在控制台中看到:

Id: 800
Main: Clear

希望对您有所帮助。