首页 > 解决方案 > 解析 JSON 数据时出错(Swift 4 Playground)

问题描述

我的 Swift Playground 不断回归

错误:无法读取数据,因为它的格式不正确。”

而且我无法弄清楚我做错了什么。下面是我的代码。

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

我认为我的结构中有一些不正确的东西,但我不知道它是什么。

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

标签: swift4xcode9swift-playground

解决方案


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

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

推荐阅读