請 AI 定義 JSON 資料對應的 Codable 型別和指定需要的資料
--
定義 JSON 資料對應的 Codable 型別並不難,只要懂得將欄位複製貼上。不過遇到多層的 JSON 時,定義多個 Codable 型別和屬性也是頗辛苦的事。
以下我們就請 GPT 4 幫忙吧。不只比較不會打錯字,而且還可指定需要的資料,AI 會聰明地判斷需定義的欄位,不會寫出 App 不需要的欄位。
- 實驗 1: 定義 JSON 對應的 Swift Codable 型別,當資料為網址時型別宣告成 URL,當資料為時間時型別宣告成 Date。
- 實驗 2: 定義 JSON 對應的 Swift Codable 型別,需要的資料是歌手名,歌名,發行日期,圖片網址,不需要的資料不要寫,當資料為網址時型別宣告成 URL,當資料為時間時型別宣告成 Date。
JSON 資料
JSON 的網址如下,資料來源為 Apple 的 RSS Feed Generator,內容為美國前十名的專輯清單。
https://rss.applemarketingtools.com/api/v2/us/music/most-played/10/albums.json
定義 JSON 對應的 Swift Codable 型別,當資料為網址時型別宣告成 URL,當資料為時間時型別宣告成 Date
根據提供的 JSON,您可以在 Swift 中使用以下 Codable 型別來解碼該 JSON:
import Foundation
struct FeedWrapper: Codable {
let feed: Feed
}
struct Feed: Codable {
let title: String
let id: URL
let author: Author
let links: [Link]
let copyright: String
let country: String
let icon: URL
let updated: Date
let results: [Result]
}
struct Author: Codable {
let name: String
let url: URL
}
struct Link: Codable {
let `self`: URL
}
struct Result: Codable {
let artistName: String
let id: String
let name: String
let releaseDate: Date
let kind: String
let artistId: String
let artistUrl: URL
let contentAdvisoryRating: String?
let artworkUrl100: URL
let genres: [Genre]
let url: URL
}
struct Genre: Codable {
let genreId: String
let name: String
let url: URL
}
// Date Formatter
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
return formatter
}()
// JSON Decoder
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
do {
let feedWrapper = try decoder.decode(FeedWrapper.self, from: jsonData)
print(feedWrapper)
} catch {
print("Error decoding JSON: \(error)")
}
這裡定義了與 JSON 對應的 Swift 結構,並使用了 URL
和 Date
型別。此外,我們使用了自定義的 DateFormatter
來解析 JSON 中的日期字符串。
以上為 AI 的回答,大致上是正確的,只有一個小小問題。時間的欄位有兩個,updated & releaseDate,它們的格式不同,因此我們要再做一些調整。
定義 JSON 對應的 Swift Codable 型別,需要的資料是歌手名,歌名,發行日期,圖片網址,不需要的資料不要寫,當資料為網址時型別宣告成 URL,當資料為時間時型別宣告成 Date
根據您提供的 JSON,您可以使用以下 Swift Codable 型別來定義您需要的資料:
import Foundation
struct AlbumResponse: Codable {
let feed: Feed
}
struct Feed: Codable {
let results: [Album]
}
struct Album: Codable {
let artistName: String
let name: String
let releaseDate: Date
let artworkUrl100: URL
}
// 使用 DateFormatter 來解析日期
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// 使用 JSONDecoder 來解析 JSON
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .formatted(dateFormatter)
do {
let albumResponse = try jsonDecoder.decode(AlbumResponse.self, from: jsonData)
print(albumResponse)
} catch {
print("Error decoding JSON: \(error)")
}
這裡我們創建了 AlbumResponse
、Feed
和 Album
結構,並且只保留了您所需的屬性。另外,我們使用了 DateFormatter
和 JSONDecoder
來解析日期和網址。