【问题标题】:Convert JSON to a Array with struct使用结构将 JSON 转换为数组
【发布时间】:2018-05-19 00:09:32
【问题描述】:

我正在尝试制作一个家庭自动化的 IOS 应用程序。我正在使用 TableViewCell 来显示信息。

我的问题是我不知道如何使用 struct 将 JSON 转换为 Array,因为我认为必须有 struct。

我的 JSON 是:

[{"namea":"TV","statea":"up_tv"},{"namea":"test","statea":"test"}]

我的代码是:

struct cellData {
let nameLabel : String!
let stateLabel : String!
}

class Main: UITableViewController {

var array = [cellData]()

override func viewDidLoad() {
    array = [cellData(nameLabel: "tv", stateLabel: "up_tv"),
             cellData(nameLabel: "tv", stateLabel: "down_tv")]

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return array.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell

    cell.nameLabel.text = array[indexPath.row].nameLabel
    cell.stateLabal.text = array[indexPath.row].stateLabel
    return cell
}

【问题讨论】:

  • 我使用HandyJSON。只需播下它,它就会让您的生活更轻松
  • 如何使用 HandyJSON
  • 在他们的 github 页面上阅读 .md

标签: ios json swift struct


【解决方案1】:

你需要 jsonDecoder

struct cellData : Decodable {
   let nameLabel : String
   let stateLabel : String

      enum CodingKeys:String,CodingKey {
        case nameLabel = "namea"
        case stateLabel = "statea"

      }
}

//

let str = """

    [{"namea":"TV","statea":"up_tv"},{"namea":"test","statea":"test"}]

"""

do {
       let cellArr = try JSONDecoder().decode([cellData].self, from: str.data(using:.utf8)!)
       print(cellArr)   //// check this 

} catch {

}

//

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell =  tableView.dequeueReusableCell(withIdentifier: "id") as TableViewCell

}

【讨论】:

  • 不,这不起作用我没有错误但没有出现表格单元格
  • 打印了数组??
  • 那是什么意思?
  • 检查代码中的打印语句,如果打印,那么您的表格设置有问题
  • 没有没有得到任何东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 2013-05-15
  • 2021-08-02
  • 1970-01-01
  • 2015-06-22
  • 2016-07-14
  • 1970-01-01
相关资源
最近更新 更多