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

时间:2016-11-18 00:22:27

标签: 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或不通过SwiftyJSON保存带有字典(departureTime,destination ...)的日程表数组?

感谢。

更新

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

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

3 个答案:

答案 0 :(得分: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
  }
}

在你的视图控制器中,你需要一个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()
        }
    }
}

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

希望它有所帮助!

答案 1 :(得分:1)

基本上你拥有的是一系列时间表。您可以使用ObjectMapper进行映射。安装它的pod并只创建一个新的Swift文件。并写下这个

import ObjectMapper

class TrainSchedules: Mappable {

var mySchedules: [Schedules]

required init?(_ map: Map) {
    mySchedules = []
}

func mapping(map: Map) {
    mySchedules             <- map["schedule"]
}
}


class Schedules: Mappable {

var departureTime: String
var destination: String
var trainType: String

required init?(_ map: Map) {

    departureTime = ""
    destination = ""
    trainType = ""
}

func mapping(map: Map) {

    departureTime           <- map["departureTime"]
    destination             <- map["destination"]
    trainType               <- map["trainType"]

}
}

现在您可以像

一样使用它
 if let data = Mapper<TrainSchedules>().map(json){
     // now data is an array containt=g all the schedules
     // access departureTimelike below
     print(data[0].departureTime)
 }

我希望它有所帮助,Letme知道你是否发现任何困难。

答案 2 :(得分:-1)

Alamofire.request("YOUR_URL", method:.post, parameters:params, encoding:URLEncoding.default, headers: nil).responseJSON { response in
    switch(response.result)
    {
    case .success(_):
        if response.result.value != nil
        {
            let dict :NSDictionary = response.result.value! as! NSDictionary
            print(dict)
            let status = dict.value(forKey: "status")as! String
            print(status)
            if(status=="1")
            {

                self.array_placeRequestId=((dict.value(forKeyPath: "result.request_id") as! NSArray).mutableCopy() as! NSMutableArray)


            }
            else
            {
               print("Something Missed")
            }
        }
        break

    case .failure(_):
        print(response.result.error)
        break
    }
}