我正在练习在 Swift 4 中解析 JSON 的新方法,并且我正在使用纽约时报 API - 我发现很难阅读 JSON 的结构,因为 API 页面只是 shows a wall of text
我已经为要提取的数据(标题、摘要)编写了一个小结构:
struct Stories: Decodable {
let title: String
let abstract: String
}
这是我为获取 JSON 而调用的函数:
func getJSON() {
let jsonUrlString = "https://api.nytimes.com/svc/topstories/v1/business.json?api-key=f4bf2ee721031a344b84b0449cfdb589:1:73741808"
guard let url = URL(string: jsonUrlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
do {
let stories = try
JSONDecoder().decode(Stories.self, from: data)
print(stories.title, stories.abstract)
} catch let jsonErr {
print("Error serializing JSON", jsonErr)
}
}.resume()
}
当我运行该应用程序时,我在控制台中看到错误消息:
Error serializing JSON keyNotFound(CodingKeys(stringValue: "title", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
所以看起来它没有找到“title”的值。我可以在这里做些什么不同的事情,我是否错误地设置了 Struct?还是我使用的 JSONDecorder 有误?
感谢您的帮助!
最佳答案
问题是 Stories
嵌套在外部 Dictionary
中,您还需要对其进行解析。
struct TopStoriesResponse: Codable {
let status:String
let results:[Story]
}
struct Story: Codable {
let title: String
let abstract: String
}
func getTopStories() {
let jsonUrlString = "https://api.nytimes.com/svc/topstories/v1/business.json?api-key=f4bf2ee721031a344b84b0449cfdb589:1:73741808"
guard let url = URL(string: jsonUrlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data, err == nil else {
print(err!)
return
}
do {
let response = try JSONDecoder().decode(TopStoriesResponse.self, from: data)
print(response.results.first?.title, response.results.first?.abstract)
} catch let jsonErr {
print("Error serializing JSON", jsonErr)
}
}.resume()
}
关于json - 序列化 JSON "keyNotFound"时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742333/