显示数组中的所有数据信息JSON

时间:2018-10-01 15:38:12

标签: ios swift api uitableview

你好,我有一个问题,我在API中得到了json文件

▿ 23 elements
  ▿ 0 : 10 elements
    ▿ 0 : 2 elements
      - key : _id
      - value : 5b9912774a324d25ac5b52d8
    ▿ 1 : 2 elements
      - key : userid
      - value : 5b76c507af724e6f7538f249
    ▿ 2 : 2 elements
      - key : __v
      - value : 0
    ▿ 3 : 2 elements
      - key : internationalFormat
      - value : +224 625 25 92 39
    ▿ 4 : 2 elements
      - key : firstname
      - value : toto
    ▿ 5 : 2 elements
      - key : lastname
      - value : tata
    ▿ 6 : 2 elements
      - key : countryCode
      - value : GN
    ▿ 7 : 2 elements
      - key : nationalFormat
      - value : 625 25 92 39
    ▿ 8 : 2 elements
      - key : created_at
      - value : 2018-09-12T13:19:51.794Z
    ▿ 9 : 2 elements
      - key : beneficiarynumber
      - value : +224625259239

但是我无法显示用户的所有信息(名字,姓氏..),这是我用来显示所有用户信息的代码

   struct Beneficiary {
        let id: Int
        let firstName: String
        let lastName: String
        let beneficiaryNumber: String
        init(_ json: [String: Any]) {
            self.id = json["_id"] as? Int ?? 0
            self.firstName = json["firstname"] as? String ?? ""
            self.lastName = json["lastname"] as? String ?? ""
            self.beneficiaryNumber = json["internationalFormat"] as? String ?? ""
        }
    }

    class HPBeneficiaryViewController {
                    //// list beneficiary /////
                    let token = HPWSLoginManager.shared().saveSuccessResponse.token
                    let idUser = sub["_id"] as! String
                    let url = URL(string: "http://51.38.36.76:40/api/v1/beneficiaries/"+idUser)!
                    var request = URLRequest(url: url)
                    request.httpMethod = "GET"
                    request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")

                    URLSession.shared.dataTask(with: request) { (data, response, error) in
                        guard let dataResponse = data, error == nil else {
                            print(error?.localizedDescription ?? "Response Error")
                            return }
                        do {
                            let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: [])
    //                        print(jsonResponse)
                            guard let jsonArray = jsonResponse as? [[String: Any]] else {
                                return
                            }
                            var model = [Beneficiary]()
                            for dic in jsonArray {
                                model.append(Beneficiary(dic))
                                cellModelArray.append(HPBeneficiaryModel(firstName: model[0].firstName, lastName: model[0].lastName, tel: model[0].beneficiaryNumber, type: .beneficiary))
                            }
    }
 let sectionModel = HPBeneficiarySectionModel(name: "Mes Beneficiaires", modelArray: cellModelArray)
                        self.sectionArray = [sectionModel]
} catch {
                        print("error serializing")
                    }
                    }.resume()

但是它只显示带有第一个用户信息的循环如何恢复所有用户?请帮助我

2 个答案:

答案 0 :(得分:0)

直接的问题是这一行:

cellModelArray.append(HPBeneficiaryModel(firstName: model[0].firstName, lastName: model[0].lastName, tel: model[0].beneficiaryNumber, type: .beneficiary))

在将新元素添加到数组的末尾时,您始终会访问model数组的第一个元素。您需要使用model.last!而不是model[0]

但是,您应该切换为使用Codable而不是手动解析JSON响应。

struct Beneficiary: Codable {
    let id: Int
    let firstName: String
    let lastName: String
    let beneficiaryNumber: String

    enum CodingKeys: String, CodingKey {
        case id = "_id", firstName = "firstname", lastName = "lastname", beneficiaryNumber = "internationalFormat"
    }
}

然后提出网络请求:

URLSession.shared.dataTask(with: request) { (data, response, error) in
    guard let dataResponse = data, error == nil else {
        print(error?.localizedDescription ?? "Response Error")
        return
    }
    do {
        let model = try JSONDecoder().decode([Beneficiary].self, from: dataResponse)
        cellModelArray.append(contentsOf: model.map({HPBeneficiaryModel(firstName: $0.firstName, lastName: $0.lastName, tel: $0.beneficiaryNumber, type: .beneficiary)}))
        let sectionModel = HPBeneficiarySectionModel(name: "Mes Beneficiaires", modelArray: cellModelArray)
        self.sectionArray = [sectionModel]
    } catch {
        print("error serializing")
    }
}.resume()

答案 1 :(得分:0)

代替这两行

    for dic in jsonArray {
        model.append(Beneficiary(dic))
        cellModelArray.append(HPBeneficiaryModel(firstName: model[0].firstName, lastName: model[0].lastName, tel: model[0].beneficiaryNumber, type: .beneficiary))
     }

使用这些:

    for dic in jsonArray {
        model.append(Beneficiary(dic))
        cellModelArray.append(HPBeneficiaryModel(firstName: dic.firstName, lastName: dic.lastName, tel: dic.beneficiaryNumber, type: .beneficiary))
    }

对于循环执行的每个循环,您已经有一个“ dic”对象。但是,您将继续访问模型model[0]的第一个元素,无论当前循环如何,该元素都会为您提供相同的对象。

我建议您也使用Codable解析JSON。这要容易得多,也很简单。 这是一个不错的教程: https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1