【问题标题】:How do i parse the json array in tableview in swift 4 using decoder我如何使用解码器在swift 4中解析tableview中的json数组
【发布时间】:2018-10-28 19:00:29
【问题描述】:

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

【问题讨论】:

  • 如何使用 Alamofire 库解析上述 JSON?请帮助我。提前谢谢你

标签: ios swift uitableview jsondecoder


【解决方案1】:

使用这些结构:

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 应声明为[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)
}

【讨论】:

  • 如何使用 Alamofire 库解析上述 JSON?请帮助我
【解决方案2】:

改成

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

你最好用大写开始结构名称,用小写vars,我留下它是为了不让你和你当前的代码混淆

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多