我在JSON解码方面遇到问题。我知道为什么会发生错误,但我不知道如何解决。该错误最有可能是在模型中某处的方括号中。从quicktype.io
获得的模型import Combine
import SwiftUI
class NewsAPI: ObservableObject {
@Published var articles: Articles = [Article]()
func loadNews() {
guard let url: URL = URL(string: "https://newsapi.org/v2/top-headlines?country=ru&category=technology&apiKey=376a97643c6c4633afe57427b71e8ebd") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
guard let json = data else { return }
let swift = try JSONDecoder().decode(Articles.self, from: json)
DispatchQueue.main.async {
self.articles = swift
}
}
catch {
print(error)
}
}
.resume()
}
}
import Foundation
public typealias Articles = [Article]
public struct Welcome: Codable, Hashable {
public let status: String?
public let totalResults: Int?
public let articles: [Article]?
public init(status: String?, totalResults: Int?, articles: [Article]?) {
self.status = status
self.totalResults = totalResults
self.articles = articles
}
}
public struct Article: Codable, Hashable {
public let source: Source?
public let author: String?
public let title: String?
public let articleDescription: String?
public let url: String?
public let urlToImage: String?
public let publishedAt: Date?
public let content: String?
enum CodingKeys: String, CodingKey {
case source, author, title
case articleDescription
case url, urlToImage, publishedAt, content
}
public init(source: Source?, author: String?, title: String?, articleDescription: String?, url: String?, urlToImage: String?, publishedAt: Date?, content: String?) {
self.source = source
self.author = author
self.title = title
self.articleDescription = articleDescription
self.url = url
self.urlToImage = urlToImage
self.publishedAt = publishedAt
self.content = content
}
}
public struct Source: Codable, Hashable {
public let id: String?
public let name: String?
public init(id: String?, name: String?) {
self.id = id
self.name = name
}
}
答案 0 :(得分:1)
将publishedAt
的类型从Date
更改为String
public let publishedAt: String?
并如下更新decoding
代码,
let welcome = try JSONDecoder().decode(Welcome.self, from: json)
DispatchQueue.main.async {
self.articles = welcome.articles
}