【问题标题】:getting crash while retrieving dict from JSON by index wise通过索引从 JSON 中检索 dict 时崩溃
【发布时间】:2019-04-08 11:18:26
【问题描述】:

我正在通过索引从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)
        }

    })
}

所以问题是,当我只收到两个 dict 响应时,我会在第三个索引上崩溃,所以如何处理错误请告诉我我最多有 4 个问题作为响应

请有人告诉我如何处理错误

【问题讨论】:

  • 不是直接访问data.array的元素,而是循环遍历它。
  • 什么是崩溃错误?
  • Thread 1: Fatal error: Index out of range 出现这样的错误,因为有时我只得到两个字典而不是四个
  • 强制解包(! 运算符)事实上的意思是:如果出于任何原因该值恰好为 nil,则崩溃。

标签: ios swift nsdictionary


【解决方案1】:

索引使用循环而不是硬编码

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

【讨论】:

  • 好吧,让我试试
  • 我想显示第一个 dict 值来标记,但在你的循环运行解决方案中,我怎样才能只为第一个 dict 然后在第二个 dict 之后获取数据
  • 我仍然无法解决我的问题,请检查我是否已用我的代码更新了问题
【解决方案2】:

你可以在 for 循环中使用 switch 来处理不同的 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)")
  }
}

}

【讨论】:

  • @VishalParmar 对此有何反馈?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 2012-08-06
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多