Hello I am creating an app with Xcode and I am having the following problem, I created this API with mockapi.io (if you enter the link you’ll see the JSON data) https://62858a2ff0e8f0bb7c057f14.mockapi.io/categorias
If you dont want to enter the link here is how it looks the JSON: (By default the JSON has an array without name as the root and that can’t be modified)
[
{
"categorie":"Fruits",
"id":"1"
},
{
"categorie":"Animals",
"id":"2"
},
{
"categorie":"Vegetables",
"id":"3"
},
{
"categorie":"Juices",
"id":"4"
},
{
"categorie":"Alcohol",
"id":"5"
},
{
"categorie":"Desserts",
"id":"6"
}
]
The problem I have is that when I try to decode the data from the API it cant’t be readed because is in the wrong format, I am trying to recreate the same code of this youtube video, but with my API: https://www.youtube.com/watch?v=sqo844saoC4
This is how my code looks like:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://62858a2ff0e8f0bb7c057f14.mockapi.io/categorias"
getData(from: url)
}
private func getData(from url: String) {
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("something went wrong")
return
}
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
}
catch {
print("failed to convert(error.localizedDescription)")
}
guard let json = result else {
return
}
print(json.items.categorie) // 👈 HERE ES WHERE THE PRINT HAPPENS
})
task.resume()
}
}
// 👇 I THINK THE PROBLEM IS DEFINITELY HERE
struct Response: Codable {
let items: ResultItem
}
struct ResultItem: Codable {
let categorie: String
}
When I execute this the terminal print: "The data couldn’t be read becouse it isn’t in the correct format."
I am pretty sure the error comes of the way I am calling the data in the structs, so my question is…? How can I exactly call the data from my API’s JSON in the code?
2
Answers
The response you get is an array of
ResultItem
s rather than a single object, so you need to decode it as an array:That said, you won’t need the
Response
struct at all and the type ofresult
will be[ResultItem]
.yes ,there is an issue in your model you don’t need to use the (Response) only use the Model (ResultItem) the JSON isn’t complex JSON like that it just array of (ResultItem)