ios - 我如何使用解码器在 swift 4 中解析 tableview 中的 json 数组

标签 ios swift uitableview jsondecoder

我是 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 中的驼峰式命名约定。此外,结构名称中的第一个字母应大写:JsonStructarradata 应声明为 [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)
}

关于ios - 我如何使用解码器在 swift 4 中解析 tableview 中的 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53035064/

相关文章:

ios - 如何将信息从它推送到的 View Controller 传输回 View Controller ?

ios - 如何使用 avfoundation 合并视频剪辑?

ios - 用 Realm Swift 中的结果中的一些项目制作一个列表

ios - 使用 watchOS 3 时出现 CloudKit 错误

ios - 如何从 Swift 3.0 中的字符串中提取单词(英文)和名称?

objective-c - UITableView 刷新数据

ios - 从 UITableView 的每个部分中选择的行(多项选择)

ios - 应用程序请求对话框中的问题(Facebook iOS SDK)

ios - 如何在 Swift 中添加 UICollectionView 的页眉和页脚 View

ios - 将数据保存到 Swift 中的一对多 CoreData 关系中