简体   繁体   中英

Create a model class and access the values from JSON response using Codable in ios swift?

I'm learning how to create a model class and using Codable protocol how to access the values for JSON response. Using Alamofire get a request for API call. Here my code

My Model class

class User:Codable{
    var topping: [Topping]?
    var name:String?
    var batters:Batter?
    var ppu:Double?
    var type:String?
    var id:Int?
}

class Topping:Codable{
    var type:String?
    var id:Int?
}
class Batter:Codable{
    var batter:[Topping]?
}


class ViewController: UIViewController {

    @IBOutlet weak var userTbl: UITableView!
    var url:String!
    var usersArray : [User] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        url = "http://www.json-generator.com/api/json/get/bQmhSwusoi?indent=2"
        Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
            .responseJSON { response in
                print("response--->",response)
                guard response.data != nil else { return }
                do{
                    self.usersArray = try JSONDecoder().decode([User].self, from: Data(response.data!))
                  self.userTbl.reloadData()
                }catch{
                    print("Failed pass the :\(error)")
                }


        }
    }

}


extension ViewController: UITableViewDelegate,UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return usersArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = userTbl.dequeueReusableCell(withIdentifier: "UserCell")
        let bUser = usersArray[indexPath.row]
        // Using bUser how can i get topping and batters values

        return cell ?? UITableViewCell()
    }

my question: Kindly view my json response and check my model class.How can i access the topping and batters values and list in the UItableview.Thanks advance.

As i said in my comment, you need to create an array of Users from data replacing this let jsonResponse = try JSONDecoder().decode(UserArr.self, from: Data(response.data!)) for let userArray: [UserArr] = try JSONDecoder().decode([UserArr].self, from: Data(response.data!))

then you need to declare an array of UserArr model which i will be renaming to User from now on

Full code

class ViewController: UIViewController {

    @IBOutlet weak var userTbl: UITableView!
    var url:String!
    var usersArray : [User] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        url = "http://www.json-generator.com/api/json/get/bQmhSwusoi?indent=2"
        Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
            .responseJSON { [weak self] response in
                guard let strongSelf = self else {
                   return
                }

                print("response--->",response)
                guard response.data != nil else { return }
                do{
                    strongSelf.usersArray = try JSONDecoder().decode([User].self, from: Data(response.data!))
                    strongSelf.userTbl.reloadData()
                }catch{
                    print("Failed pass the :\(error)")
                }


        }
    }

}

Hi Use Quicktype free online tool its very easy to use for json parsing this is the link or you can choose to search quicktype swift, I use this quite often.

https://quicktype.io/

{// sample from quicktype app online
"greeting": "Welcome to quicktype!",
"instructions": [
"Type or paste JSON here",
"Or choose a sample above",
"quicktype will generate code in your",
"chosen language to parse the sample data"
]
}
// MARK: - Welcome
struct Welcome: Codable {
let greeting: String
let instructions: [String]
}
//   let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)

Its good if u generate it yourself. Happy coding!!!!

The easiest way forward is if you in your cellForRowAt converts the properties to strings and show them in your cell

let bUser = usersArray[indexPath.row]
let toppings = bUser.topping?.compactMap {$0.type}.joined(separator: ", ")
let batters = bUser.batters?.batter?.compactMap {$0.type}.joined(separator: ", ")

cell.textLabel?.text = "Toppings: \(toppings)\nBatters: \(batters)"

Of course you need to adjust how to assign the two strings to your cell depending on how it looks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM