GeekThuG
GeekThuG

Reputation: 3

Display all data information JSON in array

I have a problem; I get well the JSON file in the API:

▿ 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

but I can not display all the information of the user (firstname, lastname ..) this is the code I implemented to display all user information:

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

but it just displays a loop with the first user information how to recover all users? Help me please.

Upvotes: 0

Views: 86

Answers (2)

Ahmed AbdAlfattah
Ahmed AbdAlfattah

Reputation: 73

instead of these two lines

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

use these :

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

You already have an object that is "dic" for each cycle the loop makes. However, you keep accessing the first element of the model model[0] which gets you the same object regardless of the current loop..

I would suggest that you also use Codable to parse your JSON. It's much easier and pretty straight forward. Here's a nice tutorial: https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54755

The immediate issue is this line:

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

You always access the first element of the model array while adding new elements to the end of the array. You need to use model.last! instead of model[0].

However, you should switch to using Codable instead of manually parsing a JSON response.

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

Then make the network request:

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

Upvotes: 0

Related Questions