json - 我无法打开图像。解析不起作用
问题描述
我无法在“图片”中打开“网址”。解析不起作用。请帮忙。谢谢你。
"images": [
{
"url": "https://ktar.com/wp-content/uploads/2020/03/ap_27df5153e3bf48198ebcfd40900446d6.jpg",
"width": 1280,
"height": 853,
"title": "Arizona reports 124 new coronavirus cases, five additional deaths",
"attribution": null
==================================================== =====
==================================================== ===== API
{
"path": "_news/2020-04-01-arizona-reports-124-new-coronavirus-cases-five-additional-deaths.md",
"title": "Arizona reports 124 new coronavirus cases, five additional deaths",
"excerpt": "The Arizona health department reported 124 new cases of coronavirus and five additional deaths on Wednesday morning, a day after the state's \"stay at home\" order went into effect.",
"heat": 145,
"tags": [
"US"
],
"type": "article",
"webUrl": "https://ktar.com/story/3056413/arizona-reports-124-new-coronavirus-cases-five-additional-deaths/",
"ampWebUrl": "https://ktar.com/story/3056413/arizona-reports-124-new-coronavirus-cases-five-additional-deaths/amp/",
"cdnAmpWebUrl": "https://ktar-com.cdn.ampproject.org/c/s/ktar.com/story/3056413/arizona-reports-124-new-coronavirus-cases-five-additional-deaths/amp/",
"publishedDateTime": "2020-04-01T09:09:00-07:00",
"updatedDateTime": null,
"provider": {
"name": "KTAR News",
"domain": "ktar.com",
"images": null,
"publishers": null,
"authors": null
},
"images": [
{
"url": "https://ktar.com/wp-content/uploads/2020/03/ap_27df5153e3bf48198ebcfd40900446d6.jpg",
"width": 1280,
"height": 853,
"title": "Arizona reports 124 new coronavirus cases, five additional deaths",
"attribution": null
}
],
"locale": "en-us",
"categories": [
"news"
],
"topics": [
"Coronavirus in US",
"Coronavirus",
"New Cases"
]
}
==================================================== ====
==================================================== ====
// SPORTNEWSVC.swift
// Hero
import Alamofire
import Kingfisher
import UIKit
class NewsVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var news = [Article]()
override func viewDidLoad() {
super.viewDidLoad()
getArticles()
}
func getArticles() {
let parameters: Parameters = ["Subscription-Key": "3009d4ccc29e4808af1ccc25c69b4d5d"]
Alamofire.request("https://api.smartable.ai/coronavirus/news/US", parameters: parameters).responseData { (response) in
guard let data = response.data else { return }
do {
// let json = try JSONSerialization.jsonObject(with: data, options: [])
// print(json)
let topHeadlinesResponse = try JSONDecoder().decode(TopHeadlinesResponse.self, from: data)
self.news = topHeadlinesResponse.news
self.collectionView?.reloadData()
} catch {
print(error)
}
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return news.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ArticleCell", for: indexPath) as? ArticleCell else { return UICollectionViewCell ()}
let article = news[indexPath.item]
cell.populate(with: article)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height: CGFloat = 277
let width = (collectionView.frame.width / 2) - 2
let size = CGSize(width: width, height: height)
return size
}
}
==================================================== ====
==================================================== ====
// Article.swift
// Hero
//
import Foundation
struct Article: Decodable {
let headline: String
let url: String?
private enum CodingKeys: String, CodingKey {
case headline = "title"
case url
}
}
==================================================== ====
==================================================== ====
//
// ArticleCell.swift
// Hero
import UIKit
import Kingfisher
class ArticleCell: UICollectionViewCell {
@IBOutlet weak var articleImageView: UIImageView!
@IBOutlet weak var headlieLabel: UILabel!
func populate(with article: Article){
headlieLabel.text = article.headline
if let url = article.url {
let url = URL(string: url)
articleImageView.kf.setImage(with: url)
}
}
}
==================================================== ====
==================================================== ====
import Foundation
struct TopHeadlinesResponse: Decodable {
let news: [Article]
}
解决方案
这个想法是您获得的 JSON 响应中的“图像”是一个数组,您需要在 Codable 结构中反映这一事实。解码魔法需要您遵循 JSON 数据结构和命名:因此,如果您在 'image' 字典中遇到字段 'width' - 您需要在 'image' 字段中有一个名为 'width' 的字段(例如,将图像作为单独的结构)
您可以在此处阅读有关 Decodables的更多信息
struct NewsApiResponse : Decodable {
let status : String
let updatedDateTime : Date?
let news : [Article]
}
struct Article : Decodable {
let id : Int
let title : String
let excerpt : String
let webUrl : String
let publishedDateTime : Date?
let images : [Image]
}
struct Image : Decodable {
let url : String
let width : Int
let height : Int
let title : String
}
推荐阅读
- powershell - Azure DevOps REST API 调用仅检索前 100 条记录并且 ContinuationToken 获取为空
- python - 使用请求将 cURL 转换为 Python
- sql - 如何根据数据表的主键分离数据表中的值?
- python - 关于使用 UCRDTW 包进行时间序列聚类
- python - 如何在字符串和翻译字符串中插入换行符以满足 PEP 8 要求?
- apache-spark - 使用 spark 从日期列中获取周末日期
- erlang - Erlang - 在外部文件中搜索特定字符串,如果不存在则追加文件
- autodesk-forge - 模型聚合:加载文档节点后扩展(选择)不起作用
- c - 为什么即使在 C 中使用 free() 后内存也没有被释放?
- python - 添加具有函数而不是数字的二维列表的项目