简体   繁体   中英

How do i parse the json array in tableview in swift 4 using decoder

I am very new to Swift 4 and I am not able to get an example on parsing JsonArray using JSONDecoder.

Below is the JSON Response which I am trying to parse from past many days.

{
  "News": [ // how can i use this news as key in swift and parse it
  {
  "intId": 354,
  "Guid": "4829b85d-56ed-46ed-b489-ddbaf0eaeb05",
  "stTitle": "Hyatt place pune CsR Thrive Activity - 2017",
  "dtUpdatedDate": "2017-06-01T11:25:00"
},
{
  "intId": 115,
  "Guid": "bcc1272c-6a47-4878-9091-5af224be494c",
  "stTitle": "CIRCULAR W.R.T. BOMBAY HIGH COURT INJUNCTION AGAINST NOVEX",
  "dtUpdatedDate": "2014-06-26T17:29:00"
}, 
{
  "intId": 120,
  "Guid": "274275db-9aa9-45d3-a00a-0f2eed662e7e",
  "stTitle": "Extension of FSSAI deadline.",
  "dtUpdatedDate": "2014-08-08T16:07:00"
     }
  ]
}

Below is my Swift code:

import UIKit

/* This is struct i have created to parse jsonArray and JsonObject*/
struct JsonFromWeb:Codable {
    let News: [jsonstruct]
}

struct jsonstruct:Codable {
    let stTitle:String
    let dtNewsDate:String
}

class ViewController:UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet var tableview: UITableView!

    // below is the array for storing the response values
    var arradata = [jsonstruct]()

    override func viewDidLoad() {
        super.viewDidLoad()
        getdata() // funcction call to load the json api
    }

    func getdata() {  // function getData to load the Api
        let url = URL(string : "http://www.hrawi.com/HrawiService.svc")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            do {
                if (error == nil) {
                    print(url!)
                    let news = try JSONDecoder().decode(JsonFromWeb.self, from: data!)
                    self.arradata = news.News
                }
            } catch {
                print("Error In Json Data")
            }
        }.resume()
    }

    //Tableview to set the JSON Data in UITableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arradata.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : TableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        //lblname to set the title from response
        cell.lblname.text = "News Title \(arradata[indexPath.row].stTitle)"
        cell.lblcapital.text = "news Date \(arradata[indexPath.row].dtNewsDate)"
        return cell
    }
}

Use these structs:

struct JSONFromWeb: Codable {
    let news: [JsonStruct]

    enum CodingKeys: String, CodingKey {
        case news = "News"
    }
}

struct JsonStruct: Codable {
    let intID: Int
    let guid, stTitle, dtUpdatedDate: String

    enum CodingKeys: String, CodingKey {
        case intID = "intId"
        case guid = "Guid"
        case stTitle, dtUpdatedDate
    }
}

Note the use of coding keys to conform to the camel case naming convention in Swift. Also, the first letter in a struct name should be uppercased: JsonStruct . arradata should then be declared as [JsonStruct] .

Now you can decode the json like so:

do {
    let jsonFromWeb = try JSONDecoder().decode(JSONFromWeb.self, from: data)
    //This web call is asynchronous, so you'll have to reload the table view
    DispatchQueue.main.async {
        self.arradata = jsonFromWeb.news
        self.tableview.reloadData()
    }
} catch {
    print(error)
}

Change this to

struct jsonstruct:Codable {
  let stTitle:String
  let dtUpdatedDate:String
}

let news = try JSONDecoder().decode(JsonFromWeb.self, from:ata!)
DispatchQueue.main.async {
  self.arradata = news.News
  self.tableview.reloadData()
}

You better start struct names with capital , and vars with small , i left it as not to confuse you with your current code

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