ios - 如何在 Swift 5 中使用 Alamofire 解析 json

标签 ios json swift xcode

我是 iOS 编程语言的新手,我正在尝试将数据从 WordPress JSON 提取到 TableView 中。我遇到了错误:

value of type 'Any' has no subscripts

当我尝试实例化数组的对象时。

这是 JSON:

[
 {
    "id": 1352,
    "date": "2019-10-16T09:30:39",
    "date_gmt": "2019-10-16T09:30:39",
    "guid": {
        "rendered": "https://wepress.comm-it.it/ddjhgtr/"
    },
    "modified": "2019-10-16T13:23:41",
    "modified_gmt": "2019-10-16T13:23:41",
    "slug": "ddjhgtr",
    "status": "publish",
    "type": "post",
    "link": "https://wepress.comm-it.it/ddjhgtr/",
    "title": "ddjhgtr",
    "content": "eryyreytyvggjggvhghhh",
    "excerpt": "eryyreyty",
    "author": 2,
    "featured_media": {
        "id": 1418,
        "url": "https://wepress.comm-it.it/wp-content/uploads/2019/10/10-62.jpeg"
    },
    "comment_status": "open",
    "ping_status": "open",
    "sticky": false,
    "template": "",
    "format": "standard",
    "meta": [],
    "categories": [
        {
            "id": 1,
            "name": "Uncategorized",
            "description": ""
        }
    ],
    "tags": [],
    "_links": {
        "self": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/posts/1352"
            }
        ],
        "collection": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/posts"
            }
        ],
        "about": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/types/post"
            }
        ],
        "author": [
            {
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/users/2"
            }
        ],
        "replies": [
            {
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/comments?post=1352"
            }
        ],
        "version-history": [
            {
                "count": 3,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/posts/1352/revisions"
            }
        ],
        "predecessor-version": [
            {
                "id": 1419,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/posts/1352/revisions/1419"
            }
        ],
        "wp:featuredmedia": [
            {
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/media/1418"
            }
        ],
        "wp:attachment": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/media?parent=1352"
            }
        ],
        "wp:term": [
            {
                "taxonomy": "category",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/categories?post=1352"
            },
            {
                "taxonomy": "post_tag",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/tags?post=1352"
            },
            {
                "taxonomy": "difficulty-level-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/difficulty-level-course?post=1352"
            },
            {
                "taxonomy": "category-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/category-course?post=1352"
            },
            {
                "taxonomy": "location-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/location-course?post=1352"
            },
            {
                "taxonomy": "duration-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/duration-course?post=1352"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
    }
 },

....(许多其他新闻对象)

{
    "id": 774,
    "date": "2019-10-07T07:30:51",
    "date_gmt": "2019-10-07T07:30:51",
    "guid": {
        "rendered": "https://wepress.comm-it.it/name-here/"
    },
    "modified": "2019-10-07T07:30:51",
    "modified_gmt": "2019-10-07T07:30:51",
    "slug": "name-here",
    "status": "publish",
    "type": "post",
    "link": "https://wepress.comm-it.it/name-here/",
    "title": "name here",
    "content": "desc here",
    "excerpt": "desc here",
    "author": 2,
    "featured_media": null,
    "comment_status": "open",
    "ping_status": "open",
    "sticky": false,
    "template": "",
    "format": "standard",
    "meta": [],
    "categories": [
        {
            "id": 1,
            "name": "Uncategorized",
            "description": ""
        }
    ],
    "tags": [],
    "_links": {
        "self": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/posts/774"
            }
        ],
        "collection": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/posts"
            }
        ],
        "about": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/types/post"
            }
        ],
        "author": [
            {
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/users/2"
            }
        ],
        "replies": [
            {
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/comments?post=774"
            }
        ],
        "version-history": [
            {
                "count": 0,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/posts/774/revisions"
            }
        ],
        "wp:attachment": [
            {
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/media?parent=774"
            }
        ],
        "wp:term": [
            {
                "taxonomy": "category",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/categories?post=774"
            },
            {
                "taxonomy": "post_tag",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/tags?post=774"
            },
            {
                "taxonomy": "difficulty-level-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/difficulty-level-course?post=774"
            },
            {
                "taxonomy": "category-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/category-course?post=774"
            },
            {
                "taxonomy": "location-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/location-course?post=774"
            },
            {
                "taxonomy": "duration-course",
                "embeddable": true,
                "href": "https://wepress.comm-it.it/wp-json/wp/v2/duration-course?post=774"
            }
        ],
        "curies": [
            {
                "name": "wp",
                "href": "https://api.w.org/{rel}",
                "templated": true
            }
        ]
      }
  }
]

目前我只想获取这些“对象”的图像 (featured_media)、标题和内容,并将它们放入 tableView 中。事实上,这是我为他们创建的结构:

新闻表示包含在 JSON 数组中的结构

struct News {
    public var id: Int
    public var title: String
    public var content: String
    public var image: FeaturedMedia
}
struct FeaturedMedia {
    public var id: Int
    public var url: String
}

这是 UITableViewCell 类:

import UIKit

class NewsTableViewCell: UITableViewCell {
    @IBOutlet weak var newsImage: UIImageView!
    @IBOutlet weak var newsTitle: UILabel!
    @IBOutlet weak var newsContent: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

这里是 UITableViewController 类:

import UIKit
import Alamofire
import Alamofire_SwiftyJSON
import SwiftyJSON

class NewsTableViewController: UITableViewController {

    var newsList: [News] = [News]()

    func parseJsonNews() {
        DispatchQueue.main.async {
            Alamofire.request("link request", method: .get).responseJSON { (response) in
                switch response.result {
                case .success(let value):
                    let news = [value]
                    print(news) // here in console it prints correctly the json, starting with [<__NSArrayI 0x6000001a9e60 ....
                    for new in news {
                        let title = new["title"]
                        print(title)
                    }
                    print(newsss)

                    self.tableView.reloadData()
                case.failure(let error):
                    print(error.localizedDescription)
                }
            })
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        parseJsonNews()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.newsList.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "newsCell", for: indexPath) as? NewsTableViewCell


        // Configure the cell...
        let imageUrl = URL.init(string: newsList[indexPath.row].featuredMedia.url)
        cell?.newsTitle.text = self.newsList[indexPath.row].title
        cell?.newsContent.text = self.newsList[indexPath.row].content
        cell.newsImage.load(url: imageUrl!)
        return cell!
    }
}

extension UIImageView {
    func load(url: URL) {
        DispatchQueue.global().async { [weak self] in
            if let data = try? Data(contentsOf: url) {
                if let image = UIImage(data: data) {
                    DispatchQueue.main.async {
                        self?.image = image
                    }
                }
            }
        }
    }
}

寻找解决方案,我刚刚找到了很多解析字典 JSON 的方法,但在这种情况下,它是一个数组,所以我修改了代码,就像你在 parseJsonNews 方法中阅读的那样,但它没有正常工作。

如有任何帮助,我们将不胜感激。

最佳答案

你可以像这样使用 Codable 解码:

let data = try? JSONDecoder().decode([DummyData].self, from: jsonData)

但首先,您所有的模型都必须符合 Codable 协议(protocol)。例如:

struct DummyData: Codable {
    let id: Int
    let date, dateGmt: String
    let modified, modifiedGmt, slug, status: String
    let type: String
    let link: String
    let title, content, excerpt: String
    let author: Int
    let commentStatus, pingStatus: String
    let sticky: Bool
    let template, format: String

    enum CodingKeys: String, CodingKey {
        case id, date
        case dateGmt = "date_gmt"
        case modified
        case modifiedGmt = "modified_gmt"
        case slug, status, type, link, title, content, excerpt, author
        case commentStatus = "comment_status"
        case pingStatus = "ping_status"
        case sticky, template, format
    }
}

关于ios - 如何在 Swift 5 中使用 Alamofire 解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58855627/

相关文章:

javascript - Angular2/Ionic - 查找数组中的重复项并组织它们

ios - 快速解析JSON数组

swift - 仅在边缘上描边 CGPath

swift - UITabBarController UINavigationController

java - Json 解析作为逻辑练习

ios - 自定义导航栏全 View 不接收触摸事件

ios - SKStore​Review​Controller,如何正确使用?

ios - 是否 URLSession.dataTask(与 :completionHandler:) always call completionHandler only once?

swift - Swift中如何为不同的Spritenode设置不同的重力?

ios - iFrameExtractor 无法使用 XCode 4.3.3 和 iOS 5.1 为 armv7 构建库