'Decoding nested JSON
I am having trouble decoding the following:
struct Categories: Codable {
var categories: [Category]
}
struct Category: Codable {
var idCategory: Int
var strCategory: String
var strCategoryThumb: String
var strCategoryDescription: String
}
let url = URL(string: "https://www.themealdb.com/api/json/v1/1/categories.php")!
let session = URLSession.shared
let dataTask = session.dataTask(with: url) { data, response, error in
if error == nil && data != nil {
let decoder = JSONDecoder()
do {
let allCategories = try decoder.decode(Categories.self, from: data!)
print(allCategories)
} catch {
print("JSON parsing error")
}
}
}
dataTask.resume()
For some reason the JSON is not decoded/printed and instead only the "JSON parsing error" is printed. What exactly is it thats going wrong in this case?
Thank you for your time.
Solution 1:[1]
you can print the error description to help you figure out what's wrong with your json use:
print(error.localizedDescription)
just after
print("JSON parsing error")
and idCategory should be String instead of Int type
struct Category: Codable {
var idCategory: String
var strCategory: String
var strCategoryThumb: String
var strCategoryDescription: String
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
