gpt4 book ai didi

ios - 我正在尝试 JSON 解码(Swift)

转载 作者:行者123 更新时间:2023-11-28 13:27:00 25 4
gpt4 key购买 nike

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)

关于ios - 我正在尝试 JSON 解码(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58184436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com