[iOS] parse JSON array then loop over in swift

I’m really confused about parsing JSON data in Swift 3. This is a lot harder than I ever expected coming from a Javascript background.

Response from API:

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

解法:

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

如果 array 有名字,像是:

{"Reason":[{"Id":1,"Value":"Reason-1"},{"Id":2,"Value":"Reason-2"},{"Id":3,"Value":"Reason-3"}]}

請服用這組 code:

            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])

            if let responseJSON = responseJSON as? [String: Any] {

                let jsonArray = responseJSON["Reason"] as? [[String: Any]]

                for json in jsonArray! {

                    let reasonKey: Int = json["Id"] as! Int

                    let reasonTitle: String = json["Value"] as! String

                    print(String(reasonKey) + ":" + reasonTitle)

                }

            }

執行結果:

1:Reason-1

2:Reason-2

3:Reason-3

 

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *