0

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 ?

1
  • you have the data , then you convert it to string and then to data again ? why ? use it directly as Data Commented May 31, 2021 at 12:31

1 Answer 1

1

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)
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.