我使用 urlsession 進行了網路請求并獲得了 json 資料,但不知道如何映射資料并填充到表視圖中。我是初學者,請幫幫我。
這是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)
}
}
uj5u.com熱心網友回復:
歡迎來到斯威夫特。如果您在 Stack Overflow(以及網路上的其他地方)上搜索這里,您會發現很多關于如何解碼 JSON Swift 的示例。
可以在此處找到 Apple 關于該主題的檔案:
編碼和解碼自定義型別
這里有一個代碼示例:
將 JSON 與自定義型別一起使用
一般來說,您需要創建一個結構體來表示解碼后的資料。該結構將從可解碼派生。您應該給它一個“CodingKeys”值,該值將定義結構中的欄位如何映射到 JSON 中的鍵。然后使用解碼器創建并填寫該結構。
JSONDecoder是用于解碼 JSON 的更新且型別安全的機制。 JSONSerialization由于型別轉換,初學者將更具挑戰性,因此我建議您堅持使用JSONDecoder
uj5u.com熱心網友回復:
基于 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 Fiction&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()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344345.html
上一篇:具有排除規則的反向字串
