-1

I'm trying to access some data from a json response in swiftui.

However, I'm getting this error:

Expected to decode Array but found a dictionary instead.", underlyingError: nil

I know that means that my code is looking for array but the json response is dictionary.

I found this: debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil)

But when I try to remove the [] from [SightingsL].self my code doesn't work and I get this error:

Cannot assign value of type 'SightingsL' to type '[SightingsL]'

which is here: self.sightingsL = decodedLists

This is my code:

Published var sightingsL = [SightingsL]()


let url = URL(string: "https://xxxx")

var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("my key", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
URLSession.shared.dataTask(with: request) {(data,response,error) in
    do {
        if let d = data {
            let decodedLists = try JSONDecoder().decode([SightingsL].self, from: d)
            DispatchQueue.main.async { [self] in
                
                self.sightingsL = decodedLists

            }
        }else {
            print("No Data")
        }
    } catch {
        print (error)
    }
    
}.resume()

and here is the JSON response:

{
  "Count": 123,
  "myflies": [
    {
      "Id": 12345,
      "Username": "SOME USERNAME",
      "Images": [
        6666,
        8888
      ],
      "userID": 123456
    }
  ]
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
drago
  • 1,148
  • 2
  • 16
  • 35

1 Answers1

2

You need

let res = try JSONDecoder().decode(Root.self, from: d)
DispatchQueue.main.async { 
  self.sightingsL = res.myflies
}
// MARK: - Root
struct Root: Codable {
    let count: Int
    let myflies: [SightingsL]

    enum CodingKeys: String, CodingKey {
        case count = "Count"
        case myflies
    }
}

// MARK: - SightingsL
struct SightingsL: Codable {
    let id: Int
    let username: String
    let images: [Int]
    let userID: Int

    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case username = "Username"
        case images = "Images"
        case userID
    }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87