【发布时间】:2021-03-01 16:37:02
【问题描述】:
所以我在解析来自 API 的数据时遇到了 JSON 解码器的另一个问题。我收到错误“解析 JSON 错误”。我叫这个api点:https://newsapi.org/v2/top-headlines?category=Science&apiKey=afd219a70f3d47f784e588548c0f7810
这是我拨打电话的代码:
var baseURL = "https://newsapi.org/v2/top-headlines?category=\(category)&apiKey=afd219a70f3d47f784e588548c0f7810"
let defaultSession = URLSession(configuration: .default)
if let url = URL(string: baseURL) {
let request = URLRequest(url: url)
let dataTask = defaultSession.dataTask(with: request) { (data, response, error) in
guard error == nil else {
print("error: ", error!)
return
}
guard let data = data else {
print("No data object")
return
}
guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
print("response is: ", response!)
return
}
guard let mime = response?.mimeType, mime == "application/json" else {
print("Wrong MIME type!")
return
}
guard let articles = try? JSONDecoder().decode(ArticleList.self, from: data) else {
print("Error Parsing JSON")
return
}
DispatchQueue.main.async {
self.articles = articles.articles
print(self.articles)
}
}
dataTask.resume()
}
}
这是我的结构:
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)
import Foundation
// MARK: - Welcome
struct ArticleList: Codable {
let status: String
let totalResults: Int
let articles: [Article]
}
// MARK: - Article
struct Article: Codable {
let source: Source
let author: String?
let title: String
let articleDescription: String?
let url: String
let urlToImage: String?
let publishedAt: Date
let content: String
enum CodingKeys: String, CodingKey {
case source, author, title
case articleDescription = "description"
case url, urlToImage, publishedAt, content
}
}
// MARK: - Source
struct Source: Codable {
let id: JSONNull?
let name: String
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
我假设我的结构有问题,这很奇怪,因为我是从 quicktype.io 获得的。有什么想法吗?
【问题讨论】:
-
在您之前关于 json 解码的两个问题中,我已经告诉您如何处理解码错误,但您根本不在乎,是吗?