gpt4 book ai didi

json - 使用 json 数据 swift 4 填充表格 View

转载 作者:行者123 更新时间:2023-11-28 05:49:37 26 4
gpt4 key购买 nike

我有 json 数据,我可以解析第一部分,即导航和名称,但是我需要将数组 children 解析为 TableView 。

{
"nav": [
{
"name": "Home",
"navigationName": "Home",
"icon": null,
"navigation": {
"URI": null,
"type": "CUSTOM",
"target": "home",
"depth": null,
"data": null,
"filters": {},
"urlStructure": {
"title": null,
"isFeatured": false,
"isCampaign": false
}
},
"styles": []
},
{
"name": "New In",
"navigationName": "New In",
"icon": null,
"navigation": {
"URI": null,
"type": "NO_LINK",
"target": "",
"depth": null,
"data": null,
"filters": {},
"urlStructure": {
"title": null,
"isFeatured": false,
"isCampaign": false
}
},
"styles": [
"linkNewin"
],
"children": [
{
"name": "New In Mens",
"navigationName": "New In Mens",
"icon": null,
"navigation": {
"URI": "/men?facet:new=latest&sort=latest",
"type": "CATEGORY",
"target": "men",
"depth": null,
"data": null,
"filters": {
"facet:new": "latest",
"sort": "latest"
},
"urlStructure": {
"title": null,
"isFeatured": false,
"isCampaign": false
}
},
"styles": [
"linkNewin"
]
},

也就是json数据。我已经解析并填充了数组导航中的名字,但无法为 Children 数组执行此操作。

到目前为止我已经创建了这个数据模型:

struct Menu: Codable {
var nav = [Menus]()
}

struct Menus: Codable {
var name: String
var children: ChildrensNames
}

struct ChildrensNames: Codable {
var name: String
}

有没有人有什么想法?

我已经让结构正常工作,所以当我添加一个断点时,我可以看到 child 的名字,但是我不知道如何访问这些并将它们添加到第二部分。下面是我的 TableView 设置

extension MenuViewController: UITableViewDataSource {

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

if section == 0{
return self.menu?.nav.count ?? 0
} else if section == 1 {
return self.menuItems?.children?.count ?? 0
} else {
return 2
}
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

if cell == nil {
cell = UITableViewCell.init(style: .value1, reuseIdentifier: "cell")
}

let navItem = self.menu?.nav[indexPath.row].name
let childItem = self.menu?.nav[indexPath.row].children


switch indexPath.section {
case 0:
cell?.textLabel?.text = navItem
break
case 1:
// cell?.textLabel?.text =

break
default:
break
}


cell?.accessoryView = UIImageView(image: UIImage(named: "icons8-chevron-right-50"))


return cell!
}

最佳答案

首先让我们重命名 Menus 以避免混淆。我们将其命名为 NavigationItem

children 的值也是 NavigationItem 的数组,并且由于某些词典没有子项,所以它是可选的。

如果结构是只读的,则只采用Decodable并将结构成员声明为常量。

struct Menu: Decodable {
let nav : [NavigationItem] // Don't declare this struct member as empty array
}

struct NavigationItem : Decodable {
let name : String
let navigationName : String
let children : [NavigationItem]?
}

关于json - 使用 json 数据 swift 4 填充表格 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53357177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com