json - 使用字典将 alamofire 中的 JSON 数据解析为数组

标签 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"]
        }
    }
}

如果我打印 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"
  }
]

现在,我如何通过或不通过 SwiftyJSON 保存带有字典(出发时间、目的地...)的时间表数组?

谢谢。

更新

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

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)
                            }
                        }
                    }
                }
        }
    }
}

最佳答案

首先,您应该创建一个类,它是您的 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
  }
}

在你的 View Controller 中,你需要一个 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()
        }
    }
}

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

希望对您有所帮助!

关于json - 使用字典将 alamofire 中的 JSON 数据解析为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40667425/

相关文章:

javascript - Highcharts 使用 json 将点添加到折线图

ios - Xcode 9.3 - NSPredicate Bool 崩溃

swift - 使用反射设置对象属性而不使用 setValue forKey

ios - 使用 post 快速 JSON 登录 REST 并获取响应示例

ios - 带有嵌套 JSON 的 valueForKeyPath

java - Gson.toJson() 项目排序错误

jquery - 将 ASP.NET Web 表单发送到 JQuery 自动完成的最佳实践

json - 如何将私钥从JWK加载到openSSL?

ios - 如何替换当前的 CALayer

ios - 如何手动将 Alamofire 添加到 xcode 项目中