如何在swift 2

时间:2016-07-28 06:45:08

标签: swift swift2

我知道有几个问题可用于同一个问题,但它们都不适用于我。 我从NSData转换为JSON的代码是

var locateData: NSData = NSData(contentsOfURL: location)!

do {

responseObject = try NSJSONSerialization.JSONObjectWithData(locateData,   options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
let arrayStatuses: NSArray = responseObject["statuses"] as! NSArray
 print("Data items count: \(arrayStatuses.count)")

}

catch _ as NSError {

}

print count alway show 1,我需要在数组

中创建可用的字典模型类

这是我的样本JSON

{
  "statuses": [
    {
      "created_at": "Wed Jul 27 07:31:26 +0000 2016",
      "name" :"shesh"
    },
    {
      "created_at": "Wed Jul 27 07:31:26 +0000 2016",
      "name" :"shesh"
    },
    {
      "created_at": "Wed Jul 27 07:31:26 +0000 2016",
      "name" :"shesh"
    },
    {
      "created_at": "Wed Jul 27 07:31:26 +0000 2016",
      "name" :"shesh"
    }]
}

2 个答案:

答案 0 :(得分:1)

首先使用原生的Swift集合类型,因为Foundation对手缺少重要的类型信息。

此代码打印键texttruncatedcreated_at

的所有值
let locateData = NSData(contentsOfURL: location)!

do {
  if let responseObject = try NSJSONSerialization.JSONObjectWithData(locateData, options: []) as? [String:AnyObject],
    arrayStatuses = responseObject["statuses"] as? [[String:AnyObject]] {
    print("Data items count: \(arrayStatuses.count)")
    for status in arrayStatuses {
      let created = status["created_at"] as! String
      let truncated = status["truncated"] as! Bool
      let text = status["text"] as! String
      print("text: \(text), created: \(created), truncated: \(truncated)")
    }
  }

} catch let error as NSError {
  print(error)
}

答案 1 :(得分:1)

您可以使用Array enumerate()

执行此操作
var locateData: NSData = NSData(contentsOfURL: location)!

do {

responseObject = try NSJSONSerialization.JSONObjectWithData(locateData,   options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
let arrayStatuses: NSArray = responseObject["statuses"] as! NSArray
  for statue in arrayStatuses.enumerate(){
    print("Statue Name : \(statue.name)")
  }

}

catch _ as NSError {

}