I have json response that I need to parse that, according to the https://newsapi.org web site, should look like:
{
"status": "ok",
"totalResults": 4498,
"articles": [{
"source": {
"id": null,
"name": "Techweekeurope.co.uk"
},
"author": null,
"title": "Top ten cloud service providers for reliability and price",
"description": "In a time where the reliability and stability of cloud service providers comes into spotlight, we pick our top ten that will help you propel your business to the next level. We recently talked about building your own local network with a Raspberry Pi starter …",
"url": "https://www.techweekeurope.co.uk/top-ten-cloud-service-providers-reliability-price/",
"urlToImage": "https://www.techweekeurope.co.uk/wp-content/uploads/2020/01/Cloud-Service-Providers.gif",
"publishedAt": "2020-01-04T16:17:00Z",
"content": "In a time where the reliability and stability of cloud service providers comes into spotlight, we pick our top ten that will help you propel your business to the next level. We recently talked about building your own local network with a Raspberry Pi starter … [+4441 chars]"
}, ...]
}
I created structures for parse it
import Foundation
struct Article: Codable {
var source: Source
var author: String?
var title: String
var description: String
var url: URL
var urlToImage: URL?
var content: String
enum codingKeys: String, CodingKey {
case source
case author
case title
case description
case url
case urlToImage
case content
}
}
struct Source: Codable {
var name: String
}
struct Articles: Codable {
var articles: [Article]
}
And I created class network service class
class NetworkService {
// MARK: - Methods
func parseJSON(from url: URL) {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
let decoder = JSONDecoder()
let articleData = try decoder.decode(Articles.self, from: data!)
print(articleData.articles.description)
} catch {
print(error)
}
}
task.resume()
}
}
In console I have this:
keyNotFound(CodingKeys(stringValue: "articles", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"articles\", intValue: nil) (\"articles\").", underlyingError: nil))