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