我如何使用解码器在Swift 4的TableView中解析JSON数组

时间:2018-10-28 19:00:29

标签: 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
    }
}

2 个答案:

答案 0 :(得分:2)

使用以下结构:

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

答案 1 :(得分:0)

将此更改为

def frequencies(text)
      words = text.split
      the_frequencies = Hash.new(0)
      words.each do |word|
        the_frequencies[word] += 1
      end
      return the_frequencies
    end

    def most_common_words(file_name, stop_words_file_name, number_of_word)
      # TODO: return hash of occurences of number_of_word most frequent words
      opened_file_string = File.open(file_name.to_s).read.downcase.strip.split.join(" ").gsub(/[^a-zA-Z \'$]/, "").gsub(/'s/, "").split
      opened_stop_file_string = File.open(stop_words_file_name.to_s).read.downcase.strip.split.join(" ").gsub(/[^a-zA-Z \']/, "").gsub(/'s/, "").split
      # declarar variables de file_name stop words.
      filtered_array = opened_file_string.reject { |n| opened_stop_file_string.include? n }
      the_frequencies = Hash.new(0)
      filtered_array.each do |word|
        the_frequencies[word] += 1
      end
      store = the_frequencies.sort_by { |_key, value| value }.reverse[0..number_of_word - 1].to_h
      store
    end

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

您最好以大写字母开头的结构名称,以small开头的vars,我保留了它,以免与您当前的代码混淆