如何解决为什么我的JSON解析无法在Swift中工作?
我尝试了许多不同的解析方法,这是最好的方法,但是当我实际解析JSON时,我遇到了“错误解析”。我还添加了用于解析它的结构。该API是newsapi,我不知道为什么解析不起作用
struct NewsFeed: Codable {
let status: String
let totalResults: Int
let articles: [Article]
}
struct Article: Codable {
let source: [String:String]
let author: String
let title: String
let description: String
let url: String
let urlToImage: String
let content: String
}
private func getData(from url: String,label: UILabel) {
URLSession.shared.dataTask(with: URL(string: url)!,completionHandler: {data,response,error in
guard let data = data,error == nil else {
print("Something went wrong")
return
}
var results: NewsFeed?
do {
results = try JSONDecoder().decode(NewsFeed.self,from: data)
}
catch {
print("Error parsing")
}
guard let json = results else {
return
}
print(json.articles[0].content)
label.text = json.articles[0].source["name"]
}).resume()
}
解决方法
NewsAPI提供的JSON中的某些字段看起来可以为空。在这种情况下,使用可编码解码JSON时,必须指定可选属性。
此外,source
属性是一个对象,因此我创建了一个对象,以使codable也知道如何解析它。
此示例似乎有效!
import Foundation
struct Newsfeed: Codable {
let status: String
let totalResults: Int
let articles: [Article]
}
struct Article: Codable {
let source: Source
let author: String?
let title: String
let description: String?
let url: URL?
let urlToImage: URL?
let content: String?
}
struct Source: Codable {
let id: String?
let name: String
}
private func getData(from url: String) {
URLSession.shared.dataTask(with: URL(string: url)!,completionHandler: {data,response,error in
guard let data = data,error == nil else {
print("Something went wrong")
return
}
var results: Newsfeed?
do {
results = try JSONDecoder().decode(Newsfeed.self,from: data)
}
catch {
print("Error parsing \(error)")
}
guard let json = results else {
return
}
print(json.articles[0].content)
}).resume()
}
let apiKey = "YOUR_API_KEY"
let urlString = "http://newsapi.org/v2/top-headlines?country=us&apiKey=\(apiKey)"
getData(from: urlString)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。