0
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. '

1
  • Don't make a key optional unless it would be nil Commented Oct 1, 2019 at 12:14

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.