ios - 如何按索引打印 JSON 字典元素?

标签 ios json swift

我写了下一个片段:

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! Dictionary<String, AnyObject>

    for i in 0...json.count - 1 {
        print(json[i]["title"])
     }
} catch let error as NSError {
    print(error)
}

在这种情况下我收到错误:

Cannot subscript a value of type 'Dictionary<String, AnyObject>' with an index of type 'Int'

我想通过索引获取元素。我一直使用 Alamofire,但今天我想以默认方式完成所有操作。谁能帮帮我?

最佳答案

你的 json是一个字典 ( Dictionary<String, AnyObject> ) 如果你想遍历一个字典你应该使用下面的语法:

for (someString, someAnyObject) in json {
    print(someString, someAnyObject)
}

更多here

关于ios - 如何按索引打印 JSON 字典元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36633203/

相关文章:

ios - IOS 中的图像、照片质量

iOS 应用内购买 : Objective-C vs. Swift

ios - MKMap View 仅显示网格不显示 map View

arrays - 未解析的标识符错误 Swift

javascript - Angular 应用程序读取不规则 json 的功能

SWIFT 2.2 DatePicker 中的最小和最大 HOUR

ios - Firebase 上传符号文件构建错误 : Unexpected argument 'ServiceAccount.json'

ios - Apple 会离线测试 iOS 应用程序吗?如果没有连接,如何处理错误?

ruby-on-rails - 如何将 ActiveModel::Serializer 应用于自定义对象?

ios - 滚动出界时 WKWebView 会发生什么