Search code examples
iosjsonswiftxcodejsondecoder

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?
}

'my Local JSON File. Looking at the file path and opening it locally, it seems that the JSON data is in the proper format. In my products.json file, the data is setup like this. '

{
    "products" : [
        {
            "id": "1",
            "product" : "Rus Salatası...",
            "image" : "imageURL...",
            "description" : "description...",
            "price" : "3.25",
            "feed" : "Bu menü 1 kişiliktir..",
            "quantity" : "1"
        }
    ]
}

'JSON Decode Code'

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)
}

'I can't get data. How can I get the data. plantDataSerialized always nil. '


Solution

  • You need a root

    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)