简体   繁体   English

在Alamofire 4中将JSON解析为对象

[英]Parsing JSON to objects in Alamofire 4

I am not a full time iOS dev and need to update some projects. 我不是一个全职的iOS开发人员,需要更新一些项目。 We are parsing JSON via Alamofire like this: 我们通过Alamofire解析JSON,如下所示:

    Alamofire.request("https://www.example.com/arc/v1/api/metro_areas/1", parameters: nil)
      .responseJSON { response in
        if let dataFromNetworking = response.result.value {
          let dict = dataFromNetworking as! NSDictionary
          let metroLocations = dict["metro_locations"]
          for d in metroLocations as! NSDictionary {  // <- this is the problem
          }
            //print("here is the length: \(self.locations.count)")
        }
   }

but I am getting a SIGABRT on the specified line above. 但是我在上面的指定行上得到了一个SIGABRT。 What is the ideal way of parsing JSON in AlamoFire 4 to build our own objects? 在AlamoFire 4中解析JSON来构建自己的对象的理想方法是什么?

Edit #1 编辑#1

Sample json: 样本json:

{
  metro_locations:[
  {
    id:1,
    name:"Joes Place"
  },
  {
    id:3,
    name:"Frank's"
  }

  ]
}

Okay based off the simplified example the below should work: 好吧,基于简化的示例,以下应该可以工作:

guard let data = response.result.value as? [String: Any],
    let metroLocations = data["metro_locations"] as? [[String: Any]] else {
        return
}

for metroLocation in metroLocations {
    print(metroLocation["id"])
    print(metroLocation["name"])
}

So what this is saying is the value is a Dictionary keyed by strings and can contain Any value which in Objective C is the same as id 所以这就是说值是一个由字符串作为键的Dictionary,并且可以包含Objective C中与id相同的任何值

Next it gets the data keyed on the "metro_locations" which in this case is an Array of Dictionary elements keyed by strings 接下来,它获取在“ metro_locations”上键入的数据,在这种情况下,该数据是由字符串键入的Dictionary元素数组

Then loop through the array and print out the values for id and name based on the information you provided above. 然后遍历数组,并根据您上面提供的信息打印出id和name的值。

This will print optionals since you would use ! 这将打印可选内容,因为您将使用! to unwrap or ideally guard let or if let to check if there was a valid value. 解包或理想情况下保护let或let让其检查是否存在有效值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM