使用字典将Alamofire中的JSON数据解析为数组 [英] Parsing JSON data from alamofire into Array with Dictionary

查看:110
本文介绍了使用字典将Alamofire中的JSON数据解析为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to parse JSON data from alamorefire as follows.

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,我的数据结构如下所示(简明扼要).

If I print json, I have a data structure like the following (stated concisely).

[
  {
    "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或不通过字典(departureTime,destination ...)保存时间表数组?

Now, how can I save the schedule array with a dictionary (departureTime, destination...) through or not through SwiftyJSON?

谢谢.

更新

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

The following is my own solution.

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的模型

First of all you should create a class that is your model of Schedule like this

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

在您的视图控制器中,您将需要一个Schedule对象的数组,并且您可以在解析您的Json之后执行以下操作:

And in your view controller your going to need an array of the Schedule object and after you could parse your Json you do it like this:

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.

Maybe is not the more efficient way to do it, but it worked for me. I'm using swift3 with xcode 8.1.

希望有帮助!

这篇关于使用字典将Alamofire中的JSON数据解析为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆