解析 JSON 数据时出错(Swift 4 游乐场)

Error when parsing JSON data (Swift 4 Playground)

我的 Swift 游乐场不断返回

Error: The data couldn't be read because it isn't in the correct format."

而且我不知道我做错了什么。下面是我的代码。

JSON 示例数据:

{
            "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"
            }
            ]
        }

游乐场代码:

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 { [=13=].meta.name })
        PlaygroundPage.current.finishExecution()
    }
    catch {
        print("Error: \(error.localizedDescription)")
        PlaygroundPage.current.finishExecution()
    }
    }.resume()

我假设我的 Struct 中有一些不正确的东西,但我不知道它是什么。

(这一段是为了让投稿工具高兴,因为它说我代码太多,其他细节不够,显然直接和简洁与投稿扫描功能不兼容)。

结构正确但根对象不是数组(去掉括号)

let posts = try decoder.decode(JsonFile.self, from: data)
print(posts.bonuses.map{[=10=].name})