Я очень новичок в Swift 4 и не могу получить пример синтаксического анализа JsonArray с использованием JSONDecoder.
Ниже приведен ответ 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
}
}