Swift 3解析JSON数组然后循环

时间:2017-08-29 13:35:36

标签: ios json swift

我对在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)
}

2 个答案:

答案 0 :(得分:2)

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)
                    }
                }
           }

答案 1 :(得分:0)

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
}