0

I'm trying to use JSON Decoder in Swift 4.1 but I keep getting

"The data couldn’t be read because it isn’t in the correct format"

and I have no idea why. I'm calling a JSON file from the Bundle.main.path and then setting that to a variable after calling it in the URL(fileURLWithPath:).

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

{
    "plant": "1015",
    "name": "SPEEDVALE",
    "key": "5035",
}

I have a struct that looks like this

struct AllData: Decodable {
    let plant: String
    let name: String
    let key: String
}

Then I have a variable that declared as this

private var x: [AllData] = []

And then the decoding block of code looks like this

do {
    let path = Bundle.main.path(forResource: "data", ofType: "json")
    let jsonData = try Data(contentsOf: URL(fileURLWithPath: path!))

    do {
        plantDataSerialized = try [JSONDecoder().decode(AllData.self, from: jsonData)]
        print(plantDataSerialized)
    } catch let error{
        print(error.localizedDescription)
    }
} catch let error {
    print(error.localizedDescription)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Simon McNeil
  • 293
  • 1
  • 13

2 Answers2

1

I think your JSON have the array of key-value pairs so you are doing decoding in a wrong way. You have to do like this:

plantDataSerialized = try JSONDecoder().decode([AllData].self, from: jsonData)

If your JSON does not have the array of key-value pairs then You need to do like this:

plantDataSerialized = try JSONDecoder().decode(AllData.self, from: jsonData)
Jogendar Choudhary
  • 3,476
  • 1
  • 12
  • 26
  • Then I get "Cannot assign value of type 'AllData' to type '[AllData]'" So I tried to make plantDataSerialized: AllData? but that didn't work. – Simon McNeil May 25 '18 at 20:14
  • @simonmcneil plantDataSerialized has the array of AllData. Means plantDataSerialized will auto get the response in [AllData]. You don't need to use another variable. – Jogendar Choudhary May 25 '18 at 20:19
1

you have error in reading file so just use it like this

guard let  jsonFile =  Bundle.main.path(forResource: "data", ofType: "json") else { return}

guard  let data = try? Data(contentsOf: URL(fileURLWithPath: jsonFile), options: []) else {return}


                do {
                    let plantDataSerialized = try [JSONDecoder().decode(AllData.self, from: data)]
                    print(plantDataSerialized)
                } catch let error{
                    print(error.localizedDescription)
                }
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35