ios - 在swiftui中访问嵌套数组值?
问题描述
我有一个正在使用的嵌套数组。
我需要从这个嵌套数组中访问一些值。
我可以使用我的代码访问 Root 值,但不能访问嵌套值。
这是我当前的代码:
// MARK: - Root
struct RootD: Codable {
let id: Int
let books: String
let regs: [SightingsD]
enum CodingKeys: String, CodingKey {
case id = "id"
case serial = "books"
case regs = "regs"
}
}
struct SightingsD: Codable, Identifiable {
public var id: Int
public var regNo: String
enum CodingKeys: String, CodingKey {
case id = "id"
case regNo = "regNo"
}
}
我可以像这样访问 Root 的东西:
if let str = String(data: data!, encoding: .utf8) {
let data = str.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
{
books = jsonArray["books"] as! String
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
}
但是我怎样才能访问类似的东西regNo
?
解决方案
你不使用JSONDecoder
guard let data = data else { return }
do {
let res = try JSONDecoder().decode(RootD.self, from:data)
res.regs.forEach {
print($0.regNo)
}
} catch {
print(error)
}
推荐阅读
- vue.js - __webpack_public_path__ 在 vuejs
- python - 如何从 zip 中提取 csv 文件并在 python 中将其保存到磁盘?
- json - JsonMappingException:不是地图,不是数组或不是枚举
- excel - 从启用宏的工作簿复制数据
- github - Hygieia Github Collector 没有获取旧的提交
- here-api - HERE 地图显示和地点 API 之间的结果不一致
- c# - 如何在 IIS windows 身份验证 C# 上添加提供程序
- wordpress - 如果任何访问者查看或访问特定页面 - WordPress,如何强制重定向到登录页面?
- c# - CreateResponse() 和 CreateErrorResponse() 有什么区别?
- apple-watch - Apple Watch 中的 Siri 快捷方式集成