2016-11-18 51 views
2

我想解析來自alamorefire的JSON數據,如下所示。從alamofire解析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保存計劃數組?

謝謝。

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

回答

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知道,如果你發現任何困難。

+0

謝謝。我在'.map'上得到了一個錯誤(上圖)。它說'不能調用'地圖'的類型參數列表(JSON) –

+0

你基本上必須將你的jsonObject(服務結果)傳遞給函數 –

3

首先你應該創建一個類,它是你的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() 
     } 
    } 
} 

也許是不是更有效的方式來做到這一點,但它對我有效。我用xcode 8.1使用swift3。

希望它有幫助!

+0

謝謝。 'dir'在self.arrSchedule.append(Schedule(jsonDic:dir as!NSDictionary))中來自哪裏? –

+0

我更新了我的答案,它是'objSchedule'而不是'dir'抱歉 – Snoobie

+0

該應用程序崩潰,並顯示以下消息:nw_host_stats_add_src recv太小,收到24,預計28。幾天後我看到了同樣的錯誤。我不記得它是什麼,但我認爲這讓我在Xcode 7下切換到了Swift 2.3。 –

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

如果您仔細閱讀問題,已經有了一個解決方案。 –