簡體   English   中英

我如何使用解碼器在Swift 4的TableView中解析JSON數組

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

我是Swift 4的新手,我無法使用JSONDecoder獲得解析JsonArray的示例。

以下是我過去幾天試圖解析的JSON響應。

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

下面是我的Swift代碼:

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

使用以下結構:

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

請注意,編碼鍵的使用符合Swift中的駝峰式命名約定。 同樣,結構名稱中的第一個字母應大寫: JsonStruct arradata應將arradata聲明為[JsonStruct]

現在您可以像這樣對json進行解碼:

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

更改為

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

您最好以大寫字母開頭結構名稱,並以small開頭vars,我保留了它,以免將您與當前代碼混淆

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM