![](/img/trans.png)
[英]Im getting an error trying to decode my json api data into a codable class
[英]Im trying JSON Decode (Swift)
struct Product: Codable {
var id: String?
var product: String?
var description: String?
var price: String?
var feed: String?
var quantity: String?
var image: String?
}
'我的本地 JSON 文件。 查看文件路徑並在本地打開它,似乎 JSON 數據格式正確。 在我的 products.json 文件中,數據是這樣設置的。 '
{
"products" : [
{
"id": "1",
"product" : "Rus Salatası...",
"image" : "imageURL...",
"description" : "description...",
"price" : "3.25",
"feed" : "Bu menü 1 kişiliktir..",
"quantity" : "1"
}
]
}
'JSON 解碼代碼'
guard let jsonFile = Bundle.main.path(forResource: "products", ofType: "json") else { return }
guard let data = try? Data(contentsOf: URL(fileURLWithPath: jsonFile), options: []) else { return }
do {
let plantDataSerialized = try JSONDecoder().decode(Product.self, from: data)
print("Test: \(plantDataSerialized)")
} catch let error{
print(error.localizedDescription)
}
'我無法獲取數據。 我怎樣才能得到數據。 PlantDataSerialized 始終為零。 '
你需要一個根
struct Root: Codable {
let products: [Product]
}
struct Product: Codable {
let id,product,description,price,feed,quantity,image: String
}
let plantDataSerialized = try JSONDecoder().decode(Root.self, from: data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.