我的API有一个这样的JSON响应:
SUCCESS: {
data = (
{
addressDescription = "";
addressLine1 = "30 xxx Street";
addressLine2 = xxx;
addressLine3 = "";
addressType = 1;
city = Lagos;
country = Nigeria;
id = xxx;
state = Lagos;
},
{
addressDescription = "AAA";
addressLine1 = "11 bbb Street,";
addressLine2 = "Ikeja";
addressLine3 = "";
addressType = 1;
city = Lagos;
country = Nigeria;
id = xxx;
state = Lagos;
}
);
我的 Swift 代码看起来像这样:
var productsArray = [AnyObject]()
Alamofire.request(URL).responseJSON {
response in
//printing response
print(response)
//getting the json value from the server
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject> {
if let innerDict = dict["data"]{
self.addyArray = innerDict as! [AnyObject]
}
}
}
如何让此数组中的各个字段(addressLine1、addressLine2 等(显示在我的 UIPickerView 中?任何帮助将不胜感激。
您可以使用
此功能从Dictionary
获取所有keys
。
self.addyArray.first.keys //return array of keys
或
self.addyArray[0].keys //return array of keys
确保您的数组不为空。
假设您按照上述 json 结构正确获得结果。
guard let dictRes = result as? [String : Any] else {
print("No data")
return
}
guard let data = dictRes["data"] as? [Any] else {
return
}
for value in data {
let dictData = value as? [String : Any]
print("addressDescription : (dictData!["addressDescription"])")
print("addressLine1 : (dictData!["addressLine1"])")
print("addressLine2 : (dictData!["addressLine2"])")
print("addressLine3 : (dictData!["addressLine3"])")
}
Alamofire.request(URL).responseJSON {
response in
//printing response
print(response)
//getting the json value from the server
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject> {
if let innerDict = dict["data"]{
for val in 0..<innerDict.count {
let dic = innerDict as! [String, AnyObject]
for vals in dic {
print(vals)
productsArray.append(vals)
}
}
}
}
}