【发布时间】:2021-05-31 12:24:06
【问题描述】:
我正在使用一个嵌套数组。
我需要访问这个嵌套数组中的一些值。
我可以使用我的代码访问根值,但不能访问嵌套值。
这是我当前的代码:
// 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 这样的东西呢?
【问题讨论】:
-
你有数据,然后你把它转换成字符串,然后再转换成数据?为什么 ?直接作为Data使用