[英]How to map json data using codable and populate to table view?
我使用 urlsession 進行了網絡請求並獲得了 json data ,但不知道如何映射數據並填充到 table view 中。 我是初學者,請幫幫我。
這是json數據:
{
page = 1;
results = (
{
adult = 0;
"backdrop_path" = "/w2PMyoyLU22YvrGK3smVM9fW1jj.jpg";
"genre_ids" = (
28,
12,
878
);
id = 299537;
"original_language" = en;
"original_title" = "Captain Marvel";
}) }
到目前為止,這是我的代碼:
var movies = [Movies]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
self.parse(json: json as! Data)
} catch {
print("JSON error: \(error.localizedDescription)")
}
func parse(json: Data) {
let decoder = JSONDecoder()
if let jsonUsers = try? decoder.decode([Movies].self, from: json) {
self.movies = jsonUsers
print(movies[0].request)
}
}
歡迎來到斯威夫特。 如果您在 Stack Overflow(以及網絡上的其他地方)上搜索這里,您會發現很多關於如何解碼 JSON Swift 的示例。
可以在此處找到 Apple 關於該主題的文檔:
這里有一個代碼示例:
一般來說,您需要創建一個結構體來表示解碼后的數據。 該結構將從可解碼派生。 您應該給它一個“CodingKeys”值,該值將定義結構中的字段如何映射到 JSON 中的鍵。 然后使用解碼器創建並填寫該結構。
JSONDecoder
是用於解碼 JSON 的更新且類型安全的機制。 JSONSerialization
將是因為類型轉換的初學者更具挑戰性,所以我建議你堅持JSONDecoder
基於 json 數據,我假設您使用的是 TMDB 的 API。
首先,您應該為結果創建一個可解碼的結構:
struct SearchResult: Decodable {
let page: Int
let results: [Movie]
let totalPages: Int
let totalResults: Int
}
其次,您應該從 API 獲取結果。 我建議您使用以下代碼進行操作:
func searchURL(withQuery query: String) -> URL? {
var components = URLComponents()
components.scheme = "https"
components.host = "api.themoviedb.org"
components.path = "/3/search/movie"
components.queryItems = [
URLQueryItem(name: "query", value: query),
URLQueryItem(name: "api_key", value: "YOUR-API-KEY")
]
return components.url
}
此函數將返回搜索結果的可選 URL,如果您使用“低俗小說”作為查詢調用它,它將返回:
https://api.themoviedb.org/3/search/movie?query=Pulp%20Fiction&api_key=YOUR-API-KEY
您可以使用它從 API 中實際獲取搜索到的短語:
func search(_ text: String, completion: @escaping (Result<[Movie], Error>) -> Void) {
if let url = getSearchURL(withQuery: text) {
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, _, _ in
if let data = data {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decodedSearchResult = try decoder.decode(SearchResult.self, from: data)
completion(.success(decodedSearchResult.results))
} catch {
completion(.failure(error))
}
}
}.resume()
}
}
以下代碼:
search("Pulp Fiction") { result in
switch result {
case .success(let items):
for item in items {
print(item.title)
}
case .failure(let error):
print(error.localizedDescription)
}
}
將打印:
Pulp Fiction
Pulp Fiction: The Facts
Pulp Fiction Art
Stealing Pulp Fiction
Pulp Fiction: the Golden Age of Storytelling
UFOTV Presents: Pulp Fiction: The Golden Age of Storytelling
Pulpe Fiction
如果要使用搜索結果填充 tableView,則應將 .success 情況替換為:
search("Pulp Fiction") { [weak self] result in
switch result {
case .success(let items):
self?.searchResults = items
DispatchQueue.main.async {
self?.tableView.reloadData()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.