json - 尝试通过 jsondecoder 解码 json 时出错
问题描述
这是我的 json,我正在尝试使用 JSONDecoder 进行解码,但由于无法做到这一点而遇到了困难。有人可以帮助什么结构,我该如何解码?
{
"Afghanistan": [
{
"city": "Kabul",
"lat": "34.5167",
"lng": "69.1833",
"state": "Kābul",
"country": "Afghanistan"
},
{
"city": "Karukh",
"lat": "34.4868",
"lng": "62.5918",
"state": "Herāt",
"country": "Afghanistan"
},
{
"city": "Zarghūn Shahr",
"lat": "32.85",
"lng": "68.4167",
"state": "Paktīkā",
"country": "Afghanistan"
}
],
"Albania": [
{
"city": "Tirana",
"lat": "41.3275",
"lng": "19.8189",
"state": "Tiranë",
"country": "Albania"
},
{
"city": "Pukë",
"lat": "42.0333",
"lng": "19.8833",
"state": "Shkodër",
"country": "Albania"
}
]}
你有什么建议解码它?
我正在尝试这个
let locationData: Countries = load("Countries.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
struct Country: Codable, Identifiable {
var id = UUID()
let city, lat, lng: String
let state: String?
let country: String
}
typealias Countries = [String: [Country]]
但是得到这个错误
无法将 Country.json 解析为 Dictionary>: keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Albania", intValue: nil), _JSONKey( stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil)) :
解决方案
由于该属性id
不是 json 的一部分,因此您需要通过添加 CodingKey 枚举来定义解码器应解码的属性Country
enum CodingKeys: String, CodingKey {
case city, lat, lng, state, country
}
CodingKey 枚举还使您有机会为您的结构属性使用更好的名称,并将它们在枚举中映射到 json 键。
struct Country: Codable, Identifiable {
var id = UUID()
let city: String
let latitude: String
let longitude: String
let state: String?
let country: String
enum CodingKeys: String, CodingKey {
case city
case latitude = "lat"
case longitude = "lng"
case state, country
}
}
推荐阅读
- python - 在 train_test_split sklearn 中随机定义训练大小
- c++ - 结构内的C ++可变数组长度
- sql - Redshift:Javascript 时间格式 Varchar 字段的日期比较
- c++ - HDF5 简单读取数据集失败
- javascript - 显示一定时间后如何隐藏或删除消息?
- python - 已部署 GAE NDB 安装
- javascript - Moment.js:将持续时间分割为年、月、周、日等
- javascript - d3.js:渐变填充是轮廓,如何使它变得立体?
- android - 使用 Surfaceview 尺寸调整相机视图
- google-pay - 使用 3ds 在网络上支付 Google Pay