我正在嘗試將所有名稱從 json url 保存到串列中,但它不起作用。
我正在使用這段代碼:
let jsonUrl = ("https://de1.api.radio-browser.info/json/stations/byname/jazz")
Alamofire.request( jsonUrl).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
for (_, subJson):(String, JSON) in swiftyJsonVar {
for (_, subJson):(String, JSON) in subJson {
let nameList = subJson["name"].stringValue
print(nameList)
}
}
}
}
我能做些什么來修復它?
uj5u.com熱心網友回復:
使用 Codable 結構使此類任務變得容易得多。
考慮一下:
//Create a struct that contains the values you are interested in
struct NameResponse: Codable{
var name: String
}
let jsonUrl = ("https://de1.api.radio-browser.info/json/stations/byname/jazz")
Alamofire.request( jsonUrl).responseData { (responseData) -> Void in
if((responseData.result.value) != nil) {
//Now decode the response data to an array of your structs
let names = try! JSONDecoder().decode([NameResponse].self, from: responseData.result.value!)
//Now you can map them to an array or process them anyway you want
let nameArray = names.map{$0.name}
print(nameArray)
}
}
編輯:
如果您需要來自 Alamofire 回應的資料,則需要呼叫.responseData處理程式而不是處理程式.responseJSON。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487360.html
