2016-11-18 110 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

如果您仔细阅读问题,已经有了一个解决方案。 –