第三方api JSON抓取練習-appleRSS
用 playground練習
這個網頁可以搜尋 apple 相關的服務,如music、podcasts等服務排名,然後產生json格式網址。
這次就以podcasts做練習
首先先選取設定
依序設定0~6
7 就是產生的JSON格式
先看一下這個網址
想要更清楚它的階層就把內容貼到這個網頁
第一層
第二層
第三層
程式碼:
比較要注意的是在解第一層時
因為第二層是字典{},所以不用加 []。
如果要解第三層,因為是 results: [..]
所以在解析的時候要是 []
完整程式碼:
struct SearchResponse: Codable {
let feed: ItemFrist
}
struct ItemFrist: Codable {
let title: String
let country: String
let results: [ItemSecond]
}
struct ItemSecond: Codable {
let artistName: String
let name: String
let artworkUrl100: URL
}
let urlString = "https://rss.applemarketingtools.com/api/v2/tw/podcasts/top/10/podcasts.json"
if let url = URL(string: urlString){
URLSession.shared.dataTask(with: url){
data, response, error in
if let data {
let decoder = JSONDecoder()
do {
let searchResponse = try decoder.decode(SearchResponse.self, from: data)
let itemfrist = searchResponse.feed
let itemsecond = searchResponse.feed.results[0]
print(itemfrist.title, itemfrist.country)
print(itemsecond.artistName, itemsecond.name, itemsecond.artworkUrl100)
} catch {
print(error)
}
}
}.resume()
}
API_JSON_appleRSS抓取練習