如何在Swift 4.2中从数组中获取字典

时间:2018-10-30 16:44:18

标签: arrays dictionary swift3

我已经看到了许多类似的问题,但是似乎没有一个与我的用例相符。

我有一个结构如下的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]()

1 个答案:

答案 0 :(得分:1)

希望此答案与您的情况相符,请在下面检查, 请勿混淆,我在文件中使用了您的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)
        }
    }

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