Reputation: 1283
I have a nested array that I'm working with.
I need to access some values from this nested array.
I can access the Root values but not the nested values with my code.
This my current code:
// 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"
}
}
And I can access the Root stuff like this:
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)
}
}
But how can I access stuff like regNo
?
Upvotes: 0
Views: 173
Reputation: 100503
You don't use 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)
}
Upvotes: 1