Swift从本地JSON文件获取数据并加载到Tableview中

时间:2019-06-06 06:00:55

标签: swift

我的情况是,我试图将本地JSON文件数据加载到tableview中。在这里,我想知道哪种方法是引用本地JSON文件的正确方法,以及如何简单地使用structcodable将其加载到Tableview中来使用它。

我想通过高度专业的方法了解以下详细信息和示例代码。

如何以适当的方式调用我的JSON文件,并且需要在struct和Codable的帮助下从JSON文件中获取数据以加载到表格视图中?

我的JSON文件

[{
    "flag": "usa.png",
    "country": "USA",
    "countryName": "United States"
}, {
    "flag": "india.png",
    "country": "IND",
    "countryName": "India"
}, {
    "flag": "uk.png",
    "country": "UK",
    "countryName": "United Kingdom"
}]

我的代码

if let path = Bundle.main.path(forResource: "sample", ofType: "json") {
    do {
          let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
          let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
          }
      } catch {
      }
}

2 个答案:

答案 0 :(得分:1)

您可以首先创建一个带有可编码的结构以匹配您的json格式

struct CountryModel: Codable{
let flag: String
let country: String
let countryName: String

 }

并且json将文件读取为

func readJson(){
    if let path = Bundle.main.path(forResource: "sample", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            let decoder = JSONDecoder()
            do {
   // get the data from JSON file with help of struct and Codable 
                let countryModel = try decoder.decode([CountryModel].self, from: data)
   // from here you can populate data in tableview
                print(countryModel)

            }catch{
                print(error) // shows error
                print("Decoding failed")// local message
            }

        } catch {
            print(error) // shows error
            print("Unable to read file")// local message
        }
    }
}

答案 1 :(得分:0)

使用以下代码

class DummyDataModel {
var flag:String?
var country:String?
var countryName:String?
static func setingModelValues(_ values: JSON)->DummyDataModel {
    let dataModel = DummyDataModel()
    dataModel.flag = values["flag"].stringValue
    dataModel.country = values["country"].stringValue
    dataModel.countryName = values["countryName"].stringValue
    return dataModel
}}

class SampleClass: UIViewController {

@IBOutlet weak var mainTableView: UITableView! {
    didSet {
        mainTableView.delegate = self
        mainTableView.dataSource = self
        mainTableView.estimatedRowHeight = 200
        mainTableView.rowHeight = UITableView.automaticDimension
    }
}
var dummyDataModel = [DummyDataModel]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.gettingJsonDataValue()

}
private func gettingJsonDataValue() {
    if let path = Bundle.main.path(forResource: "sample", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
            let jsonResponse = try JSON(data: data)
            for myData in jsonResponse.arrayValue {
                let instadata = DummyDataModel.setingModelValues(myData)
                self.dummyDataModel.append(instadata)
            }
            self.mainTableView.reloadData()

        } catch {
            // handle error
        }

    }}
extension SampleClass: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dummyDataModel.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sampleCell = tableView.dequeueReusableCell(withIdentifier: "SampleCell") as! SampleCell
        sampleCell.gettingUiUpdate(dummyDataModel[indexPath.row])
        return sampleCell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    }