简体   繁体   中英

Parsing JSON data with URLSession and Codable

i Parsing JSON with URLSession And Map it With Codable , but i cant fetch result array Inside JSON Data to show it in table view. my question it is how i can fetch result and make an object from it to use in table view .

JSON Data :

{
    "result": [
        {
            "Id": 5,
            "Title": "test",
            "EnTitle": "Story and Novel"
        },
        {
            "Id": 38,
            "Title": "test",
            "EnTitle": " Motivational"
        }
    ],
    "status": {
        "httpStatusCode": 200
    }
} 

JSON Model :

struct Result : Decodable {
    let status: status
    let result: result
}

struct status : Decodable {
    let httpStatusCode: Int
}

struct result : Decodable {
    let Id: Int
    let Title: String
    let EnTitle: String
}

View Controller:

override func viewDidLoad() {
    super.viewDidLoad()
      gettingData()
}
func gettingData(){

    let url = URL(string: URL)!
    let session = URLSession.shared
    var request = URLRequest(url: url)
    request.addValue("c9d5f944", forHTTPHeaderField: "X-test")
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            return
        }  
        guard let data = data else {
            return
        }
        do {
             let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            let response = try decoder.decode(Result.self, from: data)
            print(response)

        } catch {
            print(error)
        }
    })
    task.resume()
}

1- result key is an array let result: [Result]

// MARK: - Empty
struct Root: Codable {
    let result: [Result]
    let status: Status
}

// MARK: - Result
struct Result: Codable {
    let id: Int
    let title, enTitle: String

    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case title = "Title"
        case enTitle = "EnTitle"
    }
}

// MARK: - Status
struct Status: Codable {
    let httpStatusCode: Int
}

2- Assign array and reload the table

do {
     let decoder = JSONDecoder()
     let response = try decoder.decode(Root.self, from: data)
     self.allRes = response.result
     DispatchQueue.main.async {
       self.tableView.reloadData()
     }

} catch {
    print(error)
}

3- Table dataSource methods

var allRes = [Result]()  // add this var 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return allRes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
    let item = allRes[indexPath.row] 
    // configure cell here 
    return cell
}

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