简体   繁体   中英

How to 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 UserDic:Codable{
    var batters:Batter?
    var id:Int?
    var name:String?
    var topping:[Topping]?
    var ppu:Int?
    var type:String?
}

class Topping:Codable{
    var type:String?
    var id:Int?
}

class Batter:Codable{
    var id:Int?
    var type:String?
}

class ViewController: UIViewController {

    @IBOutlet weak var userTbl: UITableView!
    var url:String!
    var toppingVal:[Topping] = []



    override func viewDidLoad() {
            super.viewDidLoad()

            url = "http://www.json-generator.com/api/json/get/bUNhsLXzVK?indent=2"
            Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
                .responseJSON { response in
                    print("response--->",response)
                    guard response.data != nil else { return }
                    do{
                        let jsonResponse = try JSONDecoder().decode(UserDic.self, from: Data(response.data!))
                        self.toppingVal = jsonResponse.topping!
                        self.userTbl.reloadData()

                        }
                        print("reslut pass the :\(String(describing: jsonResponse.type))")
                    }catch{
                        print("Failed pass the :\(error)")
                    }


            }
}

extension ViewController: UITableViewDelegate,UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return toppingVal.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = userTbl.dequeueReusableCell(withIdentifier: "UserCell")

        let aUser = toppingVal[indexPath.row]
        cell?.textLabel?.text = String(aUser.id!)

        return cell ?? UITableViewCell()
    }
}

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

You need

// MARK: - Empty
struct UserDic: Codable {
    let topping: [Topping]
    let name: String
    let batters: Batters
    let ppu: Double
    let type: String
    let id: Int
}

// MARK: - Batters
struct Batters: Codable {
    let batter: [Topping]
}

// MARK: - Topping
struct Topping: Codable {
    let type: String
    let id: Int
}

let jsonResponse = try JSONDecoder().decode(UserDic.self, from: Data(response.data!))
self.toppingVal = jsonResponse.batters.batter
self.userTbl.reloadData()

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