首页 > 解决方案 > 如何从 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]()

标签: arraysdictionaryswift3

解决方案


我希望这个答案能与您的情况相匹配,请在下面查看,不要感到困惑,我在文件中使用了您的 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)
        }
    }

随意说我的编码中有任何错误。


推荐阅读