使用Dictionary将alamofire中的JSON数据解析为Array

El *_*ato 2 json swift alamofire

我正在尝试解析alamorefire中的JSON数据,如下所示.

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, "https://api.mynexttrainschedule.net/")
            .responseJSON { response in
                guard let object = response.result.value else {
                    print("Oh, no!!!")
                    return
                }
                let json = JSON(object);print(json)
                let schedule = json[0]["schedule"]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我打印json,我有一个如下所示的数据结构(简明扼要地说).

[
  {
    "schedule" : [
        {"departureTime" : "05:09", "destination" : "Boston", "trainType" : "Express"},
        {"departureTime" : "05:19", "destination" : "Portland", "trainType" : "Rapid"},
        {"departureTime" : "05:29", "destination" : "Boston", "trainType" : "Express""}
    ],
    "station" : "Grand Central",
    "direction" : "North"
  },
  {
    "schedule" : [
        {"departureTime" : "05:11","destination" : "Washington, "trainType" : "Express""},
        {"departureTime" : "05:23","destination" : "Baltimore, "trainType" : "Express""},
        {"departureTime" : "05:35","destination" : "Richmond, "trainType" : "Local""}
    ],
    "station" : "Grand Central",
    "direction" : "South"
  }
]
Run Code Online (Sandbox Code Playgroud)

现在,如何通过SwiftyJSON或不通过SwiftyJSON保存带有字典(departureTime,destination ...)的日程表数组?

谢谢.

UPDATE

以下是我自己的解决方案.

import Alamofire
import SwiftyJSON

class ViewController: UIViewController {
    var scheduleArray = [Dictionary<String,String>]()

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, "https://api.mynexttrainschedule.net/")
            .responseJSON { response in
                guard let object = response.result.value else {
                    print("Oh, no!!!")
                    return
                }
                let json = JSON(object)
                if let jArray = json.array {
                    if let westHolidayArray = jArray[0]["schedule"].array {
                        for train in westHolidayArray {
                            if let time = train["departureTime"].string,
                                let dest = train["destination"].string,
                                let type = train["trainType"].string {
                                let dict = ["time":time, "dest":dest, "type": type]
                                self.scheduleArray.append(d)
                            }
                        }
                    }
                }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sno*_*bie 6

首先,您应该创建一个Schedule类似于此模型的类

class Schedule: NSObject {
  var departureTime: String
  var destination: String
  var trainType: String

  init(jsonDic : NSDictionary) {
      self.departureTime = jsonDic["departureTime"] != nil ? jsonDic["departureTime"] as! String! : nil
      self.destination = jsonDic["destination"] != nil ? jsonDic["destination"] as! String! : nil
      self.trainType = jsonDic["trainType"] != nil ? jsonDic["trainType"] as! String : nil
  }
}
Run Code Online (Sandbox Code Playgroud)

在你的视图控制器中你需要一个Schedule对象的数组,在你解析你的Json之后,你会这样做:

class ScheduleController: UIViewController {

    // The two object use to show the spinner loading
    var loadingView: UIView = UIView()
    var spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)

    // Array of your objects
    var arrSchedule: [Schedule] = []


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.getInfoSchedule()
    }

    func getInfoSchedule() {
        showActivityIndicator()
        Alamofire.request("https://api.mynexttrainschedule.net/", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON {
            response in
            self.hideActivityIndicator()
            switch response.result {
            case .success:
                if let objJson = response.result.value as! NSArray? {
                    for element in objJson {
                        let data = element as! NSDictionary
                        if let arraySchedule = data["schedule"] as! NSArray? {
                            for objSchedule in arraySchedule {
                                self.arrSchedule.append(Schedule(jsonDic: objSchedule as! NSDictionary))  
                            }
                        }
                    }
                }
            case .failure(let error):
                print("Error: \(error)")
            }
        }
    }

    //Those two method serves to show a spinner when the request is in execution

    func showActivityIndicator() {
        DispatchQueue.main.async {
            self.loadingView = UIView()
            self.loadingView.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
            self.loadingView.center = self.view.center
            self.loadingView.backgroundColor = UIColor(rgba: "#111111")
            self.loadingView.alpha = 0.9
            self.loadingView.clipsToBounds = true
            self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
            self.spinner.frame = CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0)
            self.spinner.center = CGPoint(x:self.loadingView.bounds.size.width / 2, y:self.loadingView.bounds.size.height / 2)
            self.loadingView.addSubview(self.spinner)
            self.view.addSubview(self.loadingView)
            self.spinner.startAnimating()
        }
    }

    func hideActivityIndicator() {
        DispatchQueue.main.async {
            self.spinner.stopAnimating()
            self.loadingView.removeFromSuperview()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

也许这不是更有效的方法,但它对我有用.我正在使用swift3和xcode 8.1.

希望能帮助到你 !