Ios 从JSON数组中获取字段并在UIPickerView Swift中显示
我的API中有这样一个JSON响应:Ios 从JSON数组中获取字段并在UIPickerView Swift中显示,ios,arrays,alamofire,swift4,uipickerview,Ios,Arrays,Alamofire,Swift4,Uipickerview,我的API中有这样一个JSON响应: SUCCESS: { data = ( { addressDescription = ""; addressLine1 = "30 xxx Street"; addressLine2 = xxx; addressLine3 = ""; addressType = 1; city = Lagos; country =
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中?任何帮助都将不胜感激。假设您按照上述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"])")
}
您可以使用此工具从字典中获取所有键
self.addyArray.first.keys //return array of keys
或
确保您的数组不是空的。您是否正确地获得了结果??可能存在重复的
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)
}
}
}
}
}
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)
}
}
}
}
}