我正在按索引从JSON
检索数据,请允许我告诉我我的回复
{
"contraventionsData" : [
{
"id" : "1",
"contravention_id" : "314",
"question" : "Last Gas Boiler Service date (Noted on boiler)",
"Options" : [
{
"action" : "Yes"
},
{
"action" : "Further Investigation \/ Maintenance"
},
{
"action" : "N\/A"
}
]
},
{
"id" : "2",
"contravention_id" : "314",
"question" : "Is Gas Boiler due a service? (Over 12 Months)",
"Options" : [
{
"action" : "Yes"
},
{
"action" : "Maintenance Attention"
},
{
"action" : "N\/A"
}
]
},
{
"id" : "3",
"contravention_id" : "314",
"question" : "Gas heating system \/ boiler working ok?",
"Options" : [
{
"action" : "Yes"
},
{
"action" : "Maintenance Attention"
},
{
"action" : "N\/A"
}
]
},
{
"id" : "4",
"contravention_id" : "314",
"question" : "Copy of Current Service Cert give to tenant",
"Options" : [
{
"action" : "Yes"
},
{
"action" : "Tenant to be provided with copy of current service cert"
},
{
"action" : "N\/A"
}
]
}
],
"message" : "Successfully.",
"success" : "1"
}
这是我的回复,我正在按如下所示的索引进行检索
代码
func actionListAPI(){
let preferences = UserDefaults.standard
let uid = "u_id"
let acTkn = "acc_tkn"
let u_ID = preferences.object(forKey: uid)
let A_Token = preferences.object(forKey: acTkn)
let params = ["user_id": u_ID!, "access_token": A_Token!,"contraventions_id": conID!]
print(params)
SVProgressHUD.show()
Alamofire.request(reg6contraventionsquestions, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
switch response.result{
case.success(let value):
let json = JSON(value)
print(json)
let data = json["contraventionsData"]
if data == []{
}else{
let sampleArray = data.array
let firstdict = sampleArray![0]
print(firstdict)
let question = firstdict["question"].stringValue
self.lblQue1.text = question
let sampleArray1 = data.array
let firstdict1 = sampleArray1![1]
print(firstdict1)
let question1 = firstdict1["question"].stringValue
self.lblQue2.text = question1
let sampleArray2 = data.array
let firstdict2 = sampleArray2![2]
print(firstdict2)
let question2 = firstdict2["question"].stringValue
self.lblQue3.text = question2
}
SVProgressHUD.dismiss()
case.failure(let error):
print(error.localizedDescription)
}
})
}
所以问题是,当我仅收到两个字典响应时,我就在第三个索引上崩溃了,因此如何处理错误,请告诉我我最多有四个问题在响应中
如何处理错误,请有人告诉我
答案 0 :(得分:0)
索引不是使用硬编码,而是使用循环
var questions = [[String:Any]]()
if let sampleArray = data.array {
for dict in sampleArray {
print(dict)
questions.append(dict)
}
}
或更简单
if let sampleArray = data.array {
questions = sampleArray
}
或者如果您需要索引
if let sampleArray = data.array {
for (index, dict) in sampleArray.enumerated() {
print(dict, index)
questions.append(dict)
}
}
答案 1 :(得分:0)
您可以在for循环中使用一个开关来处理不同的id值,当数组较短时,这不会产生错误
for item in sampleArray {
if let id = item["id"] as? Int {
let question = item["question"] as? String ?? ""
switch id {
case 1:
self.lblQue1.text = question
case 2:
self.lblQue2.text = question
case 3:
self.lblQue3.text = question
case 4:
self.lblQue4.text = question
default:
print("error, unsupported id: \(id)")
}
}
}