【问题标题】:Swift 3 parse JSON array then loop over [duplicate]Swift 3解析JSON数组然后循环[重复]
【发布时间】:2017-08-29 13:35:36
【问题描述】:

我对在 Swift 3 中解析 JSON 数据感到非常困惑。这比我从 Javascript 背景中预期的要困难得多。

来自 API 的响应:

[
{
    "ID": 1881,
    "image": "myimageURL",
},
{
    "ID": 6333,
    "image": "myimageURL",
}
]

我的 Swift 代码:

    let images = [] as Array

override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(URL(string: "myURL")!,
        method: .get)
        .responseJSON(completionHandler: {(response) -> Void in
            print(response)
           //Parse this response. Then loop over and push value of key "image" of each object into the images array above.
    })
}

在 Javascript 中我会简单地做

let images = []
let parsed = JSON.parse(response)
for(var i in parsed){
    images.push(parsed[i].image)
}

【问题讨论】:

  • as NSArray:在 Swift 3 中,不要。首选 Swift 类型数组而不是 NSArray。

标签: ios json swift


【解决方案1】:
var images: [String] = []

Alamofire.request("https://apiserver.com/api/images") //replace url with your url
            .responseJSON { response in
                if let jsonArray = response.result.value as? [[String: Any]] {
                    print("JSON: \(json)") // serialized json response
                    for json in jsonArray {
                        let image = json["image"]
                        images.append(image)
                    }
                }
           }

【讨论】:

    【解决方案2】:
    let images = [] as NSArray
    

    上面的行可以正常工作,但为了更好的方法,您可以将上面的通用字符串数组替换为

    var images = [String]()
    

    并插入下面的代码来解析 JSON 对象

    switch(response.result) {
    case .success(_):
    
    if response.result.value != nil
    {
        let array = response.result.value as! [[String: String]]
        array.forEach{ dictionary in
            images.append(dictionary["image"] ?? "")
        }
    }
    
    case .failure(_):
    break
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多