这是我的第一个新闻应用程序项目,我想从newsapi.org解析json数据,并从Article标题和urlToImage模型填充newsTitle和newsImageUrl数组。我可以将json主体解析为控制台,但由于某些原因而无法填充数组
var newsTitleArrey = [AnyObject]()
var newsImageURLArrey = [AnyObject]()
let finalApi = "https://newsapi.org/v2/top-headlines?country=us&apiKey="
func reqToParsingData() {
guard let url = URL(string: finalApi ) else { return }
URLSession.shared.dataTask(with: url ) { ( data, response , err) in
if err == nil {
do {
let decoder = JSONDecoder()
let parsed_json_DATA = try decoder.decode(NewsModel.self, from: data! )
print( parsed_json_DATA.status as! String)
}
catch {
print( "error parsing data cause \(String(describing: err))")
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}.resume()
}
NewsModel.swift
import Foundation
struct NewsModel : Codable {
let articles : [Article]?
let status : String?
let totalResults : Int?
enum CodingKeys: String, CodingKey {
case articles = "articles"
case status = "status"
case totalResults = "totalResults"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
articles = try values.decodeIfPresent([Article].self, forKey: .articles)
status = try values.decodeIfPresent(String.self, forKey: .status)
totalResults = try values.decodeIfPresent(Int.self, forKey: .totalResults)
}
}
Article.swift
import Foundation
struct Article : Codable {
let author : String?
let content : String?
let descriptionField : String?
let publishedAt : String?
let source : Source?
let title : String?
let url : String?
let urlToImage : String?
enum CodingKeys: String, CodingKey {
case author = "author"
case content = "content"
case descriptionField = "description"
case publishedAt = "publishedAt"
case source = "source"
case title = "title"
case url = "url"
case urlToImage = "urlToImage"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
author = try values.decodeIfPresent(String.self, forKey: .author)
content = try values.decodeIfPresent(String.self, forKey: .content)
descriptionField = try values.decodeIfPresent(String.self, forKey: .descriptionField)
publishedAt = try values.decodeIfPresent(String.self, forKey: .publishedAt)
source = try Source(from: decoder)
title = try values.decodeIfPresent(String.self, forKey: .title)
url = try values.decodeIfPresent(String.self, forKey: .url)
urlToImage = try values.decodeIfPresent(String.self, forKey: .urlToImage)
}
}
Source.swift
import Foundation
struct Source : Codable {
let id : String?
let name : String?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id)
name = try values.decodeIfPresent(String.self, forKey: .name)
}
}
答案 0 :(得分:0)
您错误地解析了“源”。
在<div>
<p class="myClass"></p>
</div>
内,您正在做:
Article
但是应该是:
source = try Source(from: decoder)
示例(Swift-Playground):
source = try values.decodeIfPresent(Source.self, forKey: .source)
您可以看到,只有一项更改,一切都可以正常工作。
编辑:
将标题提取到数组中
//
// JSON.swift
// StackOverflow
//
// Created by Brandon on 2018-10-13.
// Copyright © 2018 XIO. All rights reserved.
//
import Foundation
class JSONLoader {
static let json =
"""
{
\"status\":\"ok\",
\"totalResults\":4752,
\"articles\":[
{
\"source\":{
\"id\":\"crypto-coins-news\",
\"name\":\"Crypto Coins News\"
},
\"author\":\"Press Release\",
\"title\":\"Korean Energy Trading Giant ‘STX Corporation’ Enters the Cryptocurrency Market with ‘Hanminer’ SHA256 Miners\",
\"description\":\"This is a paid-for submitted press release. CCN does not endorse, nor is responsible for any material included below and isn’t responsible for any damages or losses connected with any products or services mentioned in the press release. CCN urges readers to c…\",
\"url\":\"https://www.ccn.com/korean-energy-trading-giant-stx-corporation-enters-the-cryptocurrency-market-with-hanminer-sha256-miners/\",
\"urlToImage\":\"https://www.ccn.com/wp-content/uploads/2015/06/partner-deal.jpg\",
\"publishedAt\":\"2018-10-13T17:46:26Z\",
\"content\":\"This is a paid-for submitted press release. CCN does not endorse, nor is responsible for any material included below and isnt responsible for any damages or losses connected with any products or services mentioned in the press release. CCN urges readers to co… [+2849 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Bitcoinist.com\"
},
\"author\":\"JakeTheCryptoKing\",
\"title\":\"3 Cryptocurrencies That Could Outperform Bitcoin in the Medium-Term (GO, ICX, ETH)\",
\"description\":\"ICOs were all the rage at the height of the 2017 crypto bull-run. However, with over 9 months in bear mode, most individuals have forgotten about them entirely. But with catalysts piling up in the short-term, cryptocurrencies that focused on ICOs could make a…\",
\"url\":\"https://bitcoinist.com/3-cryptocurrencies-bitcoin-price-go-icx-eth/\",
\"urlToImage\":\"https://bitcoinist.com/wp-content/uploads/2018/10/shutterstock_566918326.jpg\",
\"publishedAt\":\"2018-10-13T17:00:52Z\",
\"content\":\"ICOs were all the rage at the height of the 2017 crypto bull-run. However, with over 9 months in bear mode, most individuals have forgotten about them entirely. But with catalysts piling up in the short-term, cryptocurrencies that focused on ICOs could make a… [+9811 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Torrentfreak.com\"
},
\"author\":\"Ernesto\",
\"title\":\"Tribler Invented ‘Paid’ Torrent Seeding Over a Decade Ago\",
\"description\":\"Over the past weeks, there has been a lot of discussion about 'paid' seeding, which is one of the new proposals from the Tron/BitTorrent team. However, this idea is far from new. The Tribler research team has been working on its 'bandwidth as currency' idea f…\",
\"url\":\"https://torrentfreak.com/tribler-invented-paid-torrent-seeding-over-a-decade-ago-181013/\",
\"urlToImage\":\"https://torrentfreak.com/images/protest-crowd-feat.jpg\",
\"publishedAt\":\"2018-10-13T16:46:39Z\",
\"content\":\"Over the past weeks, there has been a lot of discussion about 'paid' seeding, which is one of the new proposals from the Tron/BitTorrent team. However, this idea is far from new. The Tribler research team has been working on its 'bandwidth as currency' idea f… [+4532 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Fool.com\"
},
\"author\":\"newsfeedback@fool.com (Jeremy Bowman)\",
\"title\":\"1 Reason the Marijuana Boom May Not Be a Bubble\",
\"description\":\"Fears of a bubble may seem reasonable after the recent surge, but there are plenty of investors who see long-term growth here.\",
\"url\":\"https://www.fool.com/investing/2018/10/13/1-reason-the-marijuana-boom-may-not-be-a-bubble.aspx\",
\"urlToImage\":\"https://g.foolcdn.com/image/?url=https%3A%2F%2Fg.foolcdn.com%2Feditorial%2Fimages%2F496870%2Fmarijuana-jars.jpg&h=630&w=1200&op=resize\",
\"publishedAt\":\"2018-10-13T15:51:00Z\",
\"content\":\"It's high times for the marijuana industry. Cannabis stocks have surged recently, flying higher starting Aug. 15, when Constellation Brands ( NYSE:STZ ) said it would invest $4 billion in Canadian marijuana grower Canopy Growth Corporation ( NYSE:CGC ). The m… [+6556 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Madshrimps.be\"
},
\"author\":\"Stefan Mileschin\",
\"title\":\"Juniper warns about cryptocurrency implosion\",
\"description\":\"Riders of the Apocalypse ride forth Juniper Research is warning that many of the metrics in the cryptocurrency world are pointing to a market implosion. This is pretty much expected. Industry bellwether Bitcoin had seen its daily transaction volumes fall from…\",
\"url\":\"http://www.madshrimps.be/news/item/181545\",
\"urlToImage\":null,
\"publishedAt\":\"2018-10-13T14:44:06Z\",
\"content\":\"Riders of the Apocalypse ride forth Juniper Research is warning that many of the metrics in the cryptocurrency world are pointing to a market implosion. This is pretty much expected. Industry bellwether Bitcoin had seen its daily transaction volumes fall from… [+868 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Madshrimps.be\"
},
\"author\":\"Stefan Mileschin\",
\"title\":\"Juniper warns about cryptocurrency implosion\",
\"description\":\"Riders of the Apocalypse ride forth Juniper Research is warning that many of the metrics in the cryptocurrency world are pointing to a market implosion. This is pretty much expected. Industry bellwether Bitcoin had seen its daily transaction volumes fall from…\",
\"url\":\"http://www.madshrimps.be/news/item/181545?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+madshrimps+%28Madshrimps+News+RSS+Feed%29\",
\"urlToImage\":null,
\"publishedAt\":\"2018-10-13T14:44:06Z\",
\"content\":\"Riders of the Apocalypse ride forth Juniper Research is warning that many of the metrics in the cryptocurrency world are pointing to a market implosion. This is pretty much expected. Industry bellwether Bitcoin had seen its daily transaction volumes fall from… [+868 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Forbes.com\"
},
\"author\":\"Panos Mourdoukoutas, Contributor, Panos Mourdoukoutas, Contributor https://www.forbes.com/sites/panosmourdoukoutas/\",
\"title\":\"Bitcoin Price Stability -- A Bullish Or Bearish Sign\",
\"description\":\"Bitcoin has demonstrated a remarkable stability in recent weeks.\",
\"url\":\"https://www.forbes.com/sites/panosmourdoukoutas/2018/10/13/bitcoin-price-stability-a-bullish-or-bearish-sign/\",
\"urlToImage\":\"https://thumbor.forbes.com/thumbor/600x315/https%3A%2F%2Fspecials-images.forbesimg.com%2Fdam%2Fimageserve%2F1040640336%2F960x0.jpg%3Ffit%3Dscale\",
\"publishedAt\":\"2018-10-13T14:16:00Z\",
\"content\":\"Share to facebook Share to twitter Share to linkedin (Photo by Jaap Arriens/NurPhoto via Getty Images) Bitcoin has demonstrated a remarkable stability in recent weeks. Since early September, it has traded in the range of $6000-$6500. Fundamentally, price stab… [+4271 chars]\"
},
{
\"source\":{
\"id\":\"crypto-coins-news\",
\"name\":\"Crypto Coins News\"
},
\"author\":\"Pedro Febrero\",
\"title\":\"Bitcoin Opinion: This is the Quiet Before The Storm\",
\"description\":\"The air feels different during the autumn, which is around the corner here in the northern hemisphere. I must admit, I really enjoy walking down the street when it’s covered in colorful leaves. Can’t really say why, but it has always been one of those guilty …\",
\"url\":\"https://www.ccn.com/bitcoin-opinion-this-is-the-quiet-before-the-storm/\",
\"urlToImage\":\"https://www.ccn.com/wp-content/uploads/2018/10/calm-before-the-storm-bitcoin.jpg\",
\"publishedAt\":\"2018-10-13T14:00:26Z\",
\"content\":\"The air feels different during the autumn, which is around the corner here in the northern hemisphere. I must admit, I really enjoy walking down the street when its covered in colorful leaves. Cant really say why, but it has always been one of those guilty pl… [+10437 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Sys-con.com\"
},
\"author\":null,
\"title\":\"Registration Opens for @ConsenSysAndrew #Blockchain Session at @EXPOFinTech NY | #FinTech #Bitcoin #Ethereum\",
\"description\":\"Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation…\",
\"url\":\"http://java.sys-con.com/node/4326506\",
\"urlToImage\":\"http://res.cdn.sys-con.com/story/mar18/4240893/Andrew_Keys%20468.JPG\",
\"publishedAt\":\"2018-10-13T13:30:00Z\",
\"content\":\"Understanding the Implications of Blockchain Technology to Rearchitect Earth's Operating System Register for this session Here Perhaps the biggest problem we face in the world today is that there are too few people who feel that they are real stakeholders in … [+7886 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Hackernoon.com\"
},
\"author\":\"Lauren Glass\",
\"title\":\"My Crypto Journey\",
\"description\":\"My career is in Data Engineering, I hold a Bachelors of Science in Economics, and until recently I have been a major skeptic of…\",
\"url\":\"https://hackernoon.com/my-crypto-journey-55de77ba78f9\",
\"urlToImage\":\"https://cdn-images-1.medium.com/max/1200/1*GIXJK8UkuUl0Rn0bSu_XxA.png\",
\"publishedAt\":\"2018-10-13T13:16:05Z\",
\"content\":\"My career is in Data Engineering, I hold a Bachelors of Science in Economics, and until recently I have been a major skeptic of cryptocurrency. I wasnt an early adopter because I felt there were economic weaknesses that made the investment too risky. But afte… [+8469 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Newsbtc.com\"
},
\"author\":\"Nick Chong\",
\"title\":\"Bitfinex Banking Scares Continue, Bitcoin Premium Skyrockets, Tether Dumps\",
\"description\":\"Since the establishment of the first crypto-to-fiat platform, exchanges have been subject to intense scrutiny from banks, regulators, and most importantly, the consumers and investors themselves. Despite its veteran status in this nascent industry, Bitfinex i…\",
\"url\":\"https://www.newsbtc.com/2018/10/13/bitfinex-banking-scares-continue-bitcoin-premium-skyrockets-tether-dumps/\",
\"urlToImage\":\"https://s3.amazonaws.com/main-newsbtc-images/2018/10/13124533/shutterstock_1194616363.jpg\",
\"publishedAt\":\"2018-10-13T12:46:21Z\",
\"content\":\"Since the establishment of the first crypto-to-fiat platform, exchanges have been subject to intense scrutiny from banks, regulators, and most importantly, the consumers and investors themselves. Despite its veteran status in this nascent industry, Bitfinex i… [+5093 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Eastasiaforum.org\"
},
\"author\":\"Anthony van Fossen\",
\"title\":\"Passports a ticket to corruption in the Pacific Islands\",
\"description\":\"Author: Anthony van Fossen, Griffith University Since the early 1980s, Pacific island countries have sold passports to foreigners. Vanuatu is the most prominent supplier today. Passport sales in the first half of 2018 brought the country about US$39.3 million…\",
\"url\":\"http://www.eastasiaforum.org/2018/10/13/passports-a-ticket-to-corruption-in-the-pacific-islands/\",
\"urlToImage\":\"http://www.eastasiaforum.org/wp-content/uploads/2018/10/2006-04-23T000000Z_1870017854_GM1DSLHFXSAA_RTRMADP_3_SOLOMONS.jpg\",
\"publishedAt\":\"2018-10-13T11:00:23Z\",
\"content\":\"Author: Anthony van Fossen, Griffith University Since the early 1980s, Pacific island countries have sold passports to foreigners. Vanuatu is the most prominent supplier today. Passport sales in the first half of 2018 brought the country about US$39.3 million… [+5162 chars]\"
},
{
\"source\":{
\"id\":\"politico\",
\"name\":\"Politico\"
},
\"author\":\"Christian Vasquez\",
\"title\":\"West Virginia's voting experiment stirs security fears\",
\"description\":\"Overseas residents will be able to cast ballots via mobile app on Election Day, using the same tech that underlies Bitcoin. But is that a wise idea?\",
\"url\":\"https://www.politico.com/story/2018/10/13/west-virginia-voting-app-security-846130\",
\"urlToImage\":\"https://static.politico.com/9d/dd/d9c56d0a488890df5da8f209f32b/181012-phone-ap-773.jpg\",
\"publishedAt\":\"2018-10-13T10:57:24Z\",
\"content\":\"Cybersecurity and election integrity advocates say West Virginia is setting an example of all the things states shouldnt do when it comes to securing their elections. West Virginia is about to take a leap of faith in voting technology but it could put people'… [+6871 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Richmond.com\"
},
\"author\":\"\",
\"title\":\"BC-BUSINESS\",
\"description\":\"For a long time there was no news about Roger Ver's advisories. \\"Bitcoin Jesus\\" has recently signed a strategic partnership agreement between Bitcoin.com and a new fintech project Azbit.com.\",
\"url\":\"https://www.richmond.com/news/ap/bc-business/article_6df00718-03cd-56f0-908d-b1003a5cf9ac.html\",
\"urlToImage\":\"https://bloximages.newyork1.vip.townnews.com/richmond.com/content/tncms/custom/image/d3d347f2-efa0-11e6-b02b-d30e16810f0d.jpg?_dc=1486738470\",
\"publishedAt\":\"2018-10-13T10:50:11Z\",
\"content\":\"For a long time there was no news about Roger Ver's advisories. \\"Bitcoin Jesus\\" has recently signed a strategic partnership agreement between Bitcoin.com and a new fintech project Azbit.com. ZUG, Switzerland (PRWEB) October 13, 2018 -- Roger Ver, CEO of Bitco… [+1731 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Newsbtc.com\"
},
\"author\":\"Davit Babayan\",
\"title\":\"Barry Silbert: Not Bullish on ICO, How Wall Street Really Thinks About Bitcoin\",
\"description\":\"Crypto venture capitalist Barry Silbert said that he is not bullish on the projects raising funds via Initial Coin Offering, or ICO. The Digital Currency Group founder told Forbes that he philosophically supported the idea of disintermediating funding process…\",
\"url\":\"https://www.newsbtc.com/2018/10/13/barry-silbert-not-bullish-on-ico-how-wall-street-really-thinks-about-bitcoin/\",
\"urlToImage\":\"https://s3.amazonaws.com/main-newsbtc-images/2018/10/13135837/shutterstock_1008027337-1.jpg\",
\"publishedAt\":\"2018-10-13T10:48:10Z\",
\"content\":\"Crypto venture capitalist Barry Silbert said that he is not bullish on the projects raising funds via Initial Coin Offering, or ICO. The Digital Currency Group founder told Forbes that he philosophically supported the idea of disintermediating funding process… [+4632 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Sys-con.com\"
},
\"author\":null,
\"title\":\"Roger Ver Joined a New Exchange Advisory Board\",
\"description\":\"ZUG, Switzerland, Oct. 13, 2018 /PRNewswire-PRWeb/ -- Roger Ver, CEO of Bitcoin.com, and Mate Tokay, COO of Bitcoin.com, recently announced that they had joined Azbit exchange as Advisors. This news is of particular interest in the context of Roger's recent s…\",
\"url\":\"http://news.sys-con.com/node/4330900\",
\"urlToImage\":\"\",
\"publishedAt\":\"2018-10-13T10:40:23Z\",
\"content\":\"ZUG, Switzerland, Oct. 13, 2018 /PRNewswire-PRWeb/ -- Roger Ver, CEO of Bitcoin.com, and Mate Tokay, COO of Bitcoin.com, recently announced that they had joined Azbit exchange as Advisors. This news is of particular interest in the context of Roger's recent s… [+1621 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Cleantechnica.com\"
},
\"author\":\"Michael Barnard\",
\"title\":\"Smart Contract Business Underpinning (Blockchain Report Excerpt)\",
\"description\":\"A smart contract that involves contracting a payment for services to be rendered or a product to be delivered involves three separate accounts: a purchaser, a seller, and an escrow account. Escrow is a means of creating trust in a contract where there is none…\",
\"url\":\"https://cleantechnica.com/2018/10/13/smart-contract-business-underpinning-blockchain-report-excerpt/\",
\"urlToImage\":\"https://cleantechnica.com/files/2018/06/Blockchain-x-Cleantech-Report-CleanTechnica.png\",
\"publishedAt\":\"2018-10-13T10:00:11Z\",
\"content\":\"CleanTechnica Published on October 13th, 2018 | by Michael Barnard 0 October 13th, 2018 by Michael Barnard Along with our regular daily clean tech news coverage, CleanTechnica also produces in-depth reports on various aspects of clean energy and clean transpo… [+5078 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Cyware.com\"
},
\"author\":null,
\"title\":\"The biggest cryptocurrency hacks that have occurred in 2018 so far\",
\"description\":\"Since the introduction of Bitcoin in 2009, the cryptocurrency industry has rapidly gained immense popularity. However, the industry has also faced a vast variety of challenges. The blockchain’s unique characteristics, such as its anonymity and elusiveness hav…\",
\"url\":\"https://cyware.com/news/the-biggest-cryptocurrency-hacks-that-have-occurred-in-2018-so-far-a5e25c20/\",
\"urlToImage\":\"https://cystory-images.s3.amazonaws.com/shutterstock_499921516.jpg\",
\"publishedAt\":\"2018-10-13T09:36:00Z\",
\"content\":\"Since the introduction of Bitcoin in 2009, the cryptocurrency industry has rapidly gained immense popularity. However, the industry has also faced a vast variety of challenges. The blockchains unique characteristics, such as its anonymity and elusiveness have… [+4622 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Gfxbing.com\"
},
\"author\":\"Apple\",
\"title\":\"Blockchain for Business 2018 The New Industrial Revolution\",
\"description\":\"Blockchain for Business 2018: The New Industrial Revolution MP4 | Video: AVC 1280x720 | Audio: AAC 44KHz 2ch | Duration: 6 Hours | 1.75 GB Genre: eLearning | Language: English Blockchain\",
\"url\":\"http://gfxbing.com/video-tutorial/887310-blockchain-for-business-2018-the-new-industrial-revolution.html\",
\"urlToImage\":\"http://i80.fastpic.ru/big/2018/1013/7a/0cbfab8f0b72c12750baa74eb3b3e47a.jpg\",
\"publishedAt\":\"2018-10-13T09:14:29Z\",
\"content\":\"Blockchain for Business 2018: The New Industrial Revolution MP4 | Video: AVC 1280x720 | Audio: AAC 44KHz 2ch | Duration: 6 Hours | 1.75 GB Genre: eLearning | Language: English You have heard the term blockchain, right? But you are still not very clear about e… [+1135 chars]\"
},
{
\"source\":{
\"id\":null,
\"name\":\"Gfxbing.com\"
},
\"author\":\"Apple\",
\"title\":\"Bitcoin - Ethereum Trading - Watch Me Manage My Own Account\",
\"description\":\"Bitcoin - Ethereum: Trading -Watch me manage my own account MP4 | Video: AVC 1280x720 | Audio: AAC 44KHz 2ch | Duration: 3 Hours | Lec: 25 | 1.35 GB Genre: eLearning | Language: English B\",
\"url\":\"http://gfxbing.com/video-tutorial/887309-bitcoin-ethereum-trading-watch-me-manage-my-own-account.html\",
\"urlToImage\":\"http://i80.fastpic.ru/big/2018/1013/00/3160bf540c0f234a7f81463cf083d600.jpg\",
\"publishedAt\":\"2018-10-13T09:13:26Z\",
\"content\":\"Bitcoin - Ethereum: Trading -Watch me manage my own account MP4 | Video: AVC 1280x720 | Audio: AAC 44KHz 2ch | Duration: 3 Hours | Lec: 25 | 1.35 GB Genre: eLearning | Language: English Real Trader, Real CryptoCurrency, Inside look as I manage my accounts! Al… [+846 chars]\"
}
]
}
""".data(using: .utf8)!
}
struct NewsModel : Codable {
let articles : [Article]?
let status : String?
let totalResults : Int
enum CodingKeys: String, CodingKey {
case articles = "articles"
case status = "status"
case totalResults = "totalResults"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
articles = try values.decodeIfPresent([Article].self, forKey: .articles)
status = try values.decodeIfPresent(String.self, forKey: .status)
totalResults = try values.decode(Int.self, forKey: .totalResults)
}
}
struct Article : Codable {
let author : String?
let content : String?
let descriptionField : String?
let publishedAt : String?
let source : Source?
let title : String?
let url : String?
let urlToImage : String?
enum CodingKeys: String, CodingKey {
case author = "author"
case content = "content"
case descriptionField = "description"
case publishedAt = "publishedAt"
case source = "source"
case title = "title"
case url = "url"
case urlToImage = "urlToImage"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
author = try values.decodeIfPresent(String.self, forKey: .author)
content = try values.decodeIfPresent(String.self, forKey: .content)
descriptionField = try values.decodeIfPresent(String.self, forKey: .descriptionField)
publishedAt = try values.decodeIfPresent(String.self, forKey: .publishedAt)
source = try values.decodeIfPresent(Source.self, forKey: .source)
title = try values.decodeIfPresent(String.self, forKey: .title)
url = try values.decodeIfPresent(String.self, forKey: .url)
urlToImage = try values.decodeIfPresent(String.self, forKey: .urlToImage)
}
}
struct Source : Codable {
let id : String?
let name : String?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id)
name = try values.decodeIfPresent(String.self, forKey: .name)
}
}
func decodeArticles() {
do {
let res = try JSONDecoder().decode(NewsModel.self, from: JSONLoader.json)
print(res)
} catch {
print(error)
}
}
decodeArticles()
答案 1 :(得分:0)
首先从不使用多个数组作为数据源,请不要这样做。当您将源解码为结构时,您将获得分别包含有关一个项目的所有信息的对象。
第二个不与强类型系统战斗。标题数组永远不会[AnyObject]
,而是[String]
。用JSON术语来说,URL数组也是[String]
,但甚至可以即时解码为[URL]
。
所有第三项都不将所有内容都声明为可选内容。仅将结构成员声明为可选成员,其值可以为null
或其键可能丢失。如果status
不是成功,并且在这种情况下articles
将是nil
,则仅将articles
声明为可选。
您的结构太复杂,可以省略所有初始化程序和CodingKeys
。两者都是通过协议合成的。
我的建议通过适当的日期解码策略将url
解码为URL
,将publishedAt
解码为Date
。
struct NewsModel : Decodable {
let articles : [Article]?
let status : String
let totalResults : Int
}
struct Article : Decodable {
let author : String?
let content : String
let description : String
let publishedAt : Date
let source : Source
let title : String
let url : URL
let urlToImage : String?
}
struct Source : Decodable {
let id : String?
let name : String
}
和解码部分title
和urlToImage
循环打印。在集合视图中,声明一个数据源数组var articles = [Article]()
,并从Article
cellForItem
结构中获取信息。
var articles = [Article]()
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let parsedJsonData = try decoder.decode(NewsModel.self, from: data!)
let status = parsedJsonData.status
if status == "ok" {
self.articles = parsedJsonData.articles!
for article in self.articles {
let title = article.title
let urlToImage = article.urlToImage
print(title, urlToImage ?? "no URL")
}
} else {
self.articles.removeAll()
}
} catch {
print( "error parsing data cause", error)
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
其他一些注意事项:
catch
块中打印始终是前error
块的do
实例,而不是数据任务返回的错误。