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
}
]
}