【问题标题】:JSON Array to UITableView insertJSON 数组到 UITableView 插入
【发布时间】:2020-09-17 07:32:37
【问题描述】:

您好,我有一个问题,我有一个 json url,这个 json url 返回下面的 json 内容;

{"ROW”:2,”COLUMN”:[“Name”,”Surname”],"DATA”:{“Name”:[“your_name”,”your_name1”],“Surname”:[“your_surname”,”your_surname1”]}}

但对我来说,需要这种 json 格式来转换 Swift UITableView,我测试了 SwiftyJson,但对于我的问题无法正常工作。我创建了一个数组和 UITableView,并将这个数组正确插入到 UITableView,但我不知道如何将这个 json 内容添加到 UITableView。 非常感谢。

我的 Swift 代码:

let animalArray = ["Firsname","Firsname","Firsname"]


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int)-> Int{
    return animalArray.count

}



func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for:indexPath)
    cell.textLabel!.text = animalArray[indexPath.row]
    return cell
}

【问题讨论】:

  • 这种伪 CSV 结构大大降低了 JSON 解码的效率。如果您对后端有任何影响,请要求发送更多 JSON-ish 数据。
  • 非常感谢您的评论@vadian,但我无法从后端编辑此数据,为此您是否知道如何解析此 json 内容并推送 UITableView,谢谢
  • 结构意味着列数和键是动态的。因此,您必须使用JSONSerialization手动解码 JSON 并构建字典数组。相关数据在键DATA的值中,其他键/值对是多余的。
  • 非常感谢@vadian,但对于这个例子,请你写我如何从这个json文件中检索数据到数组。谢谢
  • @Linuxman JSONSerialization 为您提供字典。你编写代码把字典变成你想要的任何东西。

标签: ios arrays swift uitableview


【解决方案1】:

您应该首先在 viewDidLoad() 中获取 JSON,将其值分配给视图控制器中声明的某个 var 或 let,然后以与您刚才相同的方式使用它。 Guide to fetch and decode JSON

请注意,您的结构必须是 JSON 的精确副本。既然是

{ 
  "ROW”: 2,
  ”COLUMN”:[“Name”,”Surname”],
  "DATA”: { “Name”: [“your_name”,”your_name1”],
            “Surname”: [“your_surname”,”your_surname1”] }
}

你的结构必须是

struct JSONStruct: Codable {
    var ROW: Int
    var COLUMN: [String]
    var DATA: Dictionary<String: [String]>
}

【讨论】:

  • 非常感谢@Andery,但我写道,这没有返回任何数据。我的代码是: struct DATA : Decodable { let Firstname: String } let url = "MYURL" let urlObj = URL(string: url) URLSession.shared.dataTask(with: urlObj!) {(data,response,error) in do { var countries = try JSONDecoder().decode([DATA].self, from: data!) for DATA 在国家 { print (DATA.Firstname) } } catch { } }
  • 先尝试使用此工具验证您的 JSON:jsonlint.com
  • Yes 显示 Valid JSON
  • @Linuxman,看来我知道问题出在哪里了。看看我的最新更新。
猜你喜欢
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2017-03-19
  • 2018-05-04
  • 1970-01-01
相关资源
最近更新 更多