json - 用 json 数据 swift 4 填充表视图
问题描述
我有 json 数据,我可以解析第一部分,即导航和名称,但是我需要将数组解析children
为表格视图。
{
"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
}
有没有人有任何想法?
我已经让结构工作了,所以当我在其中添加断点时,我可以看到孩子的名字,但是我不知道如何访问这些并将它们添加到第二部分。下面是我的表格视图设置
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
。
key 的值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]?
}
推荐阅读
- javascript - cropper.js 无法初始化没有显示任何错误
- blockchain - 有交易的测试网吗?我想测试交易我新创建的代币
- azure - 如何限制函数访问 Azure 中的存储帐户
- agora.io - 如何将录制选项添加到我的视频会议应用程序
- java - 如何使用 Maven 将所有依赖项放入 JAR 文件中的一个文件夹中?
- javascript - 在 Jquery ui 手风琴 doset 工作中动态添加内容
- firebase - Flutter Web)注册后用户模型无法上传到firestore
- php - 谷歌翻译 api 注册多个词汇表
- properties - 如何在 cloudformation 属性中使用条件?
- tomcat - Kartoza/geoserver tomcat 问题