swift - 如何在没有第三方库的情况下在 swift 2 中解析 JSON 数据

标签 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 {

}

打印计数总是显示 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"
    }]
}

最佳答案

首先,始终使用原生 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)
}

关于swift - 如何在没有第三方库的情况下在 swift 2 中解析 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38628899/

相关文章:

ios - 单元测试 Swift 2.0、@testable 导入和方案目标问题

swift - 如何使 Swift 2 函数抛出异常

swift - 在 Swift 中链接可选

Swift 类继承输出说明

ios - Xcode Swift 代码折叠/折叠

ios - Swift 上的数组比较未按预期工作

ios - crashlytics 中应用程序的不同包标识符

ios - 发布 NSNotification 时更新自定义单元 UIButton 标题

json - 使用 InputReader 解析包含数组的 JSON 字符串?

swift - dispatch_group_notify block 抛出的 "Realm accessed from incorrect thread"异常