如何使用Codable从Bundle解码JSON文件

问题描述

我不太确定在可以开始使用JSON数据的状态下出错的地方。我有一些想法,但不确定如何克服它们。

这是我用来保存国家/地区数据的国家/地区结构:

struct Country: Codable {
    var id: Int
    var country: String
    var capital: String
    var nationalLanguage: String
    var population: Int
}

这是我用来解码该数据的代码。这是在我的viewDidLoad方法中并且正在构建,但是在应用启动后立即崩溃并抛出我的致命错误:

let url = Bundle.main.url(forResource: "countries",withExtension: "json")!
        do {
            let jsonData = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let countryStruct = try decoder.decode(Country.self,from: jsonData)
            print(countryStruct.capital)
        } catch {
            fatalError("Unable to load data")
        }
    }

这是我的JSON文件的一个片段,我将其拖放到项目的导航中:

[
    {
    “id”: 1,“country”: “United States”,“capital”: “Washington D.C.”,“nationalLanguage”: “English”,“population”: 328,239,523
},{
    “id”: 2,“country”: “Canada”,“capital”: “Ottawa”,“nationalLanguage”: [“English”,“French”],“population”: 37,151,728
},

我想使用的主视图控制器顶部也有一个countryArray,但我不确定。

var countryArray = [Country]()

编辑:已解决-我在JSON文件中使用的引号是“智能”引号,而不是普通引号。

解决方法

您的JSON无效。

  • 您提到的引号无效
  • 逗号分隔符不允许为double值或float值

此外,您的JSON不一致,因为在json数组的第一个对象中,nationalLanguage属性是简单的String,而在第二个对象中,则是String s数组。 / p>

因此,您的JSON可能应更改为以下内容:

[
    {
        "id": 1,"country": "United States","capital": "Washington D.C.","nationalLanguage": ["English"],"population": 328239.523
    },{
        "id": 2,"country": "Canada","capital": "Ottawa","nationalLanguage": ["English","French"],"population": 37151.728
    }
]

您的模型将更改为以下形式:

struct Country: Codable {
    var id: Int
    var country: String
    var capital: String
    var nationalLanguage: [String]
    var population: Double
}

解码将是:

if let url = Bundle.main.url(forResource: "countries",withExtension: "json") {
    do {
        let jsonData = try Data(contentsOf: url)
        let decoder = JSONDecoder()
        let countryStruct = try decoder.decode([Country].self,from: jsonData)
        print(countryStruct.capital)
    } catch {
        print(error)
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...