arrays - 如何从 Swift 4.2 中的数组中获取字典
问题描述
我见过许多类似的问题,但似乎没有一个与我的用例相匹配。
我有一个结构如下的 json 文件:
{
"Trains": [{
"Car": "8",
"Destination": "Glenmont",
"DestinationCode": "B11",
"DestinationName": "Glenmont",
"Group": "1",
"Line": "RD",
"LocationCode": "A06",
"LocationName": "Van Ness-UDC",
"Min": "3"
}, {
"Car": "6",
"Destination": "Shady Gr",
"DestinationCode": "A15",
"DestinationName": "Shady Grove",
"Group": "2",
"Line": "RD",
"LocationCode": "A06",
"LocationName": "Van Ness-UDC",
"Min": "3"
}]
}
我正在尝试获取每列火车的字典。我已经尝试过这个(在其他努力中),但我无法理解它。这是我的代码:
jsonArray = [try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers)] as! [String]
for train in jsonArray {
print(train["name"])
}
这不编译。
我的 jsonArray 设置为:
var jsonArray = [Any]()
解决方案
我希望这个答案能与您的情况相匹配,请在下面查看,不要感到困惑,我在文件中使用了您的 JSON 响应。
if let path = Bundle.main.path(forResource: "file", ofType: "json") {
do {
let data1 = try Data(contentsOf: URL(fileURLWithPath: path), options: [])
let jsonDic = try JSONSerialization.jsonObject(with: data1, options: .mutableContainers) as? [String:Any]
guard let dic = jsonDic else { return}
if let dict = dic["Trains"] as? [[String:Any]]{
print(dict)
}
} catch {
print(error as NSError)
}
}
如果您想使用解码器,请使用它。
struct Result: Decodable {
let Trains:[transaction]
}
struct transaction: Decodable {
let Car:String
let Destination:String
let DestinationCode:String
}
var result = [Result]()
if let path = Bundle.main.path(forResource: "file", ofType: "json") {
do {
let data1 = try Data(contentsOf: URL(fileURLWithPath: path), options: [])
let decoder = JSONDecoder()
result = [try decoder.decode(Result.self, from: data1)]
print(result)
} catch {
print(error)
}
}
随意说我的编码中有任何错误。
推荐阅读
- python - 来自几列的饼图 - Python
- javascript - 私信提及会员 | 不和谐.js
- python - 如何组合字符串并使 int 打印已设置的值
- swiftui - SwiftUI:在 Text 之间添加仅 1 的填充会创建一个巨大的填充 - 如何实际制作一个小填充?
- c# - Asp.net Core MVC 角色和授权
- python - 从 Pandas 数据框中的列中解析日期
- swift - 调用特定于目标的函数时,多个目标的 Swift 类无法编译
- flutter - BackdropScaffold frontLayer的元素不出现时如何解决?
- vue.js - Vuex 状态获取器在 vue 3 组合 API 中不起作用
- javascript - Axios/Fetch 回调在事件循环中去哪里了?