繁体   English   中英

我正在尝试 JSON 解码(Swift)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM