Reputation: 340
My Swift Playground keeps returning
Error: The data couldn't be read because it isn't in the correct format."
and I can't figure out what I'm doing wrong. Below is my code.
JSON Sample Data:
{
"meta": {
"name":"Tour of Honor Bonus Listing",
"version":"18.1.4"
},
"bonuses": [
{
"bonusCode":"AZ1",
"category":"ToH",
"name":"Anthem Tour of Honor Memorial",
"value":1,
"city":"Anthem",
"state":"AZ",
"flavor":"Flavor Text Goes Here"
}
]
}
Playground Code:
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
struct JsonFile: Codable {
struct Meta: Codable {
let name: String
let version: String
}
struct JsonBonuses: Codable {
let bonusCode: String
let category: String
let name: String
let value: Int
let city: String
let state: String
let flavor: String
}
let meta: Meta
let bonuses: [JsonBonuses]
}
let url = URL(string: "http://www.tourofhonor.com/BonusData.json")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
PlaygroundPage.current.finishExecution()
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print("Error: invalid HTTP response code")
PlaygroundPage.current.finishExecution()
}
guard let data = data else {
print("Error: missing data")
PlaygroundPage.current.finishExecution()
}
// feel free to uncomment this for debugging data
// print(String(data: data, encoding: .utf8))
do {
let decoder = JSONDecoder()
let posts = try decoder.decode([JsonFile].self, from: data)
print(posts.map { $0.meta.name })
PlaygroundPage.current.finishExecution()
}
catch {
print("Error: \(error.localizedDescription)")
PlaygroundPage.current.finishExecution()
}
}.resume()
I assume I have something in my Struct incorrect, but I can't figure out what it is.
(This paragraph is to make the submission tool happy because it says I have too much code and not enough other details. Apparently being direct and succinct is not compatible with the submission scanning function).
Upvotes: 0
Views: 234
Reputation: 285069
The struct is correct but the root object is not an array (remove the brackets)
let posts = try decoder.decode(JsonFile.self, from: data)
print(posts.bonuses.map{$0.name})
Upvotes: 1