Parsing JSON data from alamofire into Array with Dictionary

后端 未结 3 2004
名媛妹妹
名媛妹妹 2021-01-20 01:26

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

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {
    ove         


        
相关标签:
3条回答
  • 2021-01-20 01:48
    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
        }
    }
    
    0 讨论(0)
  • 2021-01-20 01:49

    Basically what you have is an array of schedules. You can map it using ObjectMapper. Install its pod and just create a new Swift file. and Write this

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

    Now you can use it like

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

    I hope it helps, Letme know if you find any difficulty.

    0 讨论(0)
  • 2021-01-20 01:51

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

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

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

    Hope it helps !

    0 讨论(0)
提交回复
热议问题