【问题标题】:parse JSON Array from GET request Alamofire Swift 2从 GET 请求中解析 JSON 数组 Alamofire Swift 2
【发布时间】:2015-11-22 17:08:37
【问题描述】:

我是 Swift 新手,我的任务是从 GET 请求中获取数据并将其数据呈现​​在 UI 上。以下是我的代码:

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
        let base64Credentials = credentialData.base64EncodedStringWithOptions([])
        let headers = ["Authorization": "Basic \(base64Credentials)"]
        Alamofire.request(.GET, myUrl, headers: headers)
           .responseJSON{ JSON in
                if let jsonResult = JSON as? Array<Dictionary<String, String>> {
                 let title = jsonResult[0]["title"]
                    print(title)
                }
        }

我能够通过请求获取数据,但我不知道如何以某种格式(可能是 json 数组)解析 JSON 对象,以便以后在 TableView 中呈现。请帮忙

数据示例:

[ { “标题”:“索尼”, “内容”:“技术内容”, “图片”:“http://google.com/content/device.jpg?06” }, { "title": "Nexus", "content": "Nexus 6 是一个新的开始", “图片”:“http://google.com/content/device.jpg?01” } ]

【问题讨论】:

  • JSON 解析是一项常见的任务,如果您在 SO 或其他地方进行简单搜索,您应该能够找到很多信息。这是来自SO
  • 很好的问题,而且你还没有得到明确的答案,这是谷歌上的最高结果,这证明了尽管势利的开发者拒绝投票,但它是一个多么棒的问题。

标签: ios arrays json swift2 alamofire


【解决方案1】:

JSON 数据可以用不同的形式表示。它可以编码为字符串或转换为平台上已知的数据类型。 json 的主要组成部分是数组、关联数组(或字典)和值。

您正在显示的 swift 结构如下所示。

这是一个数组。此处显示的数组内容以 [] 开头和结尾,例如 [1,2,3] 将是一个整数数组。

数组中的数据是字典列表。字典以 {} 开头和结尾。比如 {"key":"value"}

这些词典包含键“title”、“content”和“image”。

因为您从 alamo 文件中请求了 responseJSON,您将返回一个已解析的结构,您只需像读取普通数组和字典一样读取它。

您应该阅读本文档,了解如何使用上述逻辑制作安全代码。 http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial

【讨论】:

  • 感谢您的回复。我明白你的意思,但我无法解决问题。
  • 感谢您的回复。我明白你的意思,但我无法解决问题。我正在尝试使用: {result in do{ let arrayresult = try NSJSONSerialization.JSONObjectWithData(data, options:[]) } catch let error as ErrorType { ...} if let items = arrayresult as NSArray { let item = items [0] 作为 NSDictionary{ 让内容 = 项目 [“内容”] 作为? NSString ...} 但出现错误.. 你能为这种情况提供一个工作代码吗(Swift 2)?
  • 使用此代码:Alamofire.request(.GET, url, headers: headers) .responseJSON{result in do{ let arrayresult = try NSJSONSerialization.JSONObjectWithData(result, options :[]) 作为! [String:AnyObject] } catch let error as ErrorType { print("error")}
    我发现一个错误:无法将 'Response' 类型的值转换为预期的参数类型 'NSData'跨度>
  • 第二部分是: if let items = arrayresult as NSArray { if let item = items[0] as NSDictionary { let content = item [“内容”]作为? NSString 让 image = item["image"] as? NSString 让 title = item["title"] as? NSString} } 错误:使用未解析的标识符'arrayresult'
  • 看起来响应是 nserror 的 anyobject 类型。请求似乎有错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多