我有以下问题需要从JSON对象检索URL数组,以便从我的应用程序中的电子商务网站下载产品的所有图片。
我得到的JSON看起来像这样:
[
{
........
........
.........
........
"images": [
{
"id": 976,
"date_created": "2016-08-10T15:16:49",
"date_modified": "2016-08-10T15:16:49",
"src": "https://i2.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-familia.jpg?fit=600%2C600&ssl=1",
"name": "canasta-familia",
"alt": "",
"position": 0
}
],
.......
.......
.......
到目前为止,我只能从数组中获取一个字符串。
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
.responseJSON { response in
if let jsonValue = response.result.value {
let jsonObject = JSON(jsonValue)
var jsonArray = jsonObject[0]["images"][0]["src"].stringValue
print(jsonArray)
}
}
给了我这个
https://xx.xx.xx/xxxx.xxxxx.xxxx/xx-xxxxx/uploads/2016/07/canasta-familia.jpg?fit=600%2C600&ssl=1
但我需要的是访问“图像”中的所有元素& “src”不仅仅是两者索引的第一个元素。
我该怎么做?
有什么想法吗?
答案 0 :(得分:3)
第1步:
创建自定义对象以表示图片。我们称之为"图片"。
struct Picture {
let id:Int
let date_created:String
let date_modified:String
let src:String
let name:String
let alt:String
let position:Int
}
第2步:
创建一个数组来保存所有产品图片。确保注意创建它的范围。理想情况下,它应该在您的下载功能之外。
var productPictures = [Picture]()
第3步:
下载您的JSON文件,为每个图像制作一个Picture结构,并将每个图片添加到您的productPictures数组中。
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
self.productPictures.removeAll()
guard let json = response.result.value as? [String:Any] else {
print("couldn't retrieve json as a dictionary")
return
}
guard let images = json["images"] as? [AnyObject] else {
print("there was a problem accessing the images key")
return
}
for image in images {
guard let id = image["id"] as? Int,
let date_created = image["date_created"] as? String,
let date_modified = image["date_modified"] as? String,
let src = image["src"] as? String,
let name = image["name"] as? String,
let alt = image["alt"] as? String,
let position = image["position"] as? Int
else {
print("There was a problem accessing one of the picture variables, or it was missing")
continue
}
let newPicture = Picture(id: id,
date_created: date_created,
date_modified: date_modified,
src: src,
name: name,
alt: alt,
position: position)
self.productPictures.append(newPicture)
}
case .failure(let error):
print("could not download and retrieve product images. An error occurred: \(error)")
return
}
}
现在你有一个完整的Picture结构数组,每个结构包含从你的JSON下载中提取的所有必要信息。
注意强>
这并不使用SwiftyJSON,但它应该可以工作并为您提供相同的预期结果。我希望这有帮助!
答案 1 :(得分:1)
以下代码行应该可行,因为我已经使用实际数据集测试了自己。
import Alamofire
import SwiftyJSON
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
.responseJSON { response in
if let jsonValue = response.result.value {
let jsonObject = JSON(jsonValue)
if let array = jsonObject.array {
for i in 0..<array.count {
if let images = array[i]["images"].array {
for i in 0..<images.count {
let src = images[i]["src"]
print(src) // save src in an array or whatever
}
}
}
}
}