Swift TableViewCell from Array to JSON



所以我让它在 swift 代码中从固定数组返回数据。

但是现在我想将该固定数据切换为此 JSON 中的数据 - https://api.drn1.com.au/api-access/news

但是,因为我在当前代码中使用了关键字 news,所以我发现很难调用这个 JSON,因为我需要使用关键字 news,因为 JSONP 有

{"新闻":...}

现在这是我知道都需要更改它以注入 JSON 数据的当前代码。

func createArray() -> [News] {
return [News(title: "Hello") , News(title: "how") , News(title: "You")]  
}

起初,我认为这就像更改我现在播放的 json 获取数据一样简单。

这是脚本(结构部分不包括在此(:

@objc func nowplaying(){
let jsonURLString = "https://api.drn1.com.au/station/playing"
guard let feedurl = URL(string: jsonURLString) else { return }
URLSession.shared.dataTask(with: feedurl) { (data,response,err) in
guard let data = data else { return }
do {
let nowplaying = try JSONDecoder().decode(Nowplayng.self, from: data)
nowplaying.data.forEach {
DispatchQueue.main.async {
self.artist.text = nowplaying.data.first?.track.artist
self.song.text = nowplaying.data.first?.track.title
}
}
} catch let jsonErr {
print("error json ", jsonErr)
}
}.resume()
}

我将如何使用以下代码来做到这一点

struct NewsData: Decodable{
let news: [articalData]
}
struct articalData: Decodeable{
let title: String
}

获取新闻:

@objc func newsfetch(){
let jsonURLString = "https://api.drn1.com.au/api-access/news"
guard let feedurl = URL(string: jsonURLString) else { return }

URLSession.shared.dataTask(with: feedurl) { (data,response,err) in
guard let news = data else { return }
do {
let news = try JSONDecoder().decode(NewsData.self, from: news)
NewsData.news.forEach {
print(NewsData.news.title)
}
} catch let jsonErr{
print("error json ", jsonErr)
}
}.resume()
}

但是当我这样做时,我收到错误

第一个1 出现在第一个结构中

struct NewsData

: Decodable{//错误类型'NewsData'不 符合"可解码"协议

第二个错误

struct articalData: Decodeable{//使用未声明的类型 "可解码">

第三个错误

NewsData.news.forEach {//闭包参数列表的上下文类型 期望 1 个参数,不能隐式忽略插入"_ in" 实例成员"news"不能用于类型"新闻数据">

print(NewsData.news.title(//实例成员 'news' 不能用于类型 'NewsData' 和 '[articalData]' 类型的值没有成员 'title'
}

我知道我想要实现的目标与我现在正在播放的 JSON 不同,但它们的格式非常相似。欢迎任何建议。

第一个和第二个错误是由拼写错误引起的(在玛丽娜的回答中已经提到过(。

这是两倍Decodable.并请用起始大写字母命名结构

struct NewsData: Decodable {
let news: [ArticleData]
}
struct ArticleData: Decodable {
let title: String
}

第三个错误实际上是两个错误。您必须在实例news(而不是类型News上(调用forEach,并且必须在闭包中使用参数。

我重命名了一些变量以避免混淆

guard let data = data else { return }
do {
let newsData = try JSONDecoder().decode(NewsData.self, from: data)
newsData.news.forEach { item in
print(item.title)                           
}

或使用速记参数名称语法更短

newsData.news.forEach { print($0.title) }

请阅读错误消息。它们中的大多数都非常清晰和描述性。

你的结构类型有一个错别字,在你的第二个错误中解释过:

struct articalData: Decodeable{//使用未声明的类型 'Decodeable'

这应该是:

struct NewsData: Decodable{
let news: [articalData]
}
struct articalData: Decodable{
let title: String
}

最新更新