【发布时间】:2018-09-30 16:53:41
【问题描述】:
我正在尝试解码此 JSON,但到目前为止我一直无法解码。我正在尝试遍历专辑数组并获取 JSON,但我必须先浏览不同的字典。我怎样才能解决这个问题?我不得不从结果转移到专辑匹配,最后是专辑,但它仍然期待字典。我该如何构建它并获得正确的格式?
完全错误:
(_AD7BA6EDB44A00F25A39B8A21DBEFF83 中的 CodingKeys).image, Foundation.(_12768CA107A31EF2DCE034FD75B541C9 中的 _JSONKey)(stringValue: "Index 0", intValue: Optional(0))], debugDescription: "期望解码字符串,但找到了字典。",底层错误:无))
JSON:
{
"results": {
"opensearch:Query": {
"#text": "",
"role": "request",
"searchTerms": "believe",
"startPage": "1"
},
"opensearch:totalResults": "113802",
"opensearch:startIndex": "0",
"opensearch:itemsPerPage": "50",
"albummatches": {
"album": [
{
"name": "Believe",
"artist": "Disturbed",
"url": "https:\/\/www.last.fm\/music\/Disturbed\/Believe",
"image": [
{
"#text": "https:\/\/lastfm-img2.akamaized.net\/i\/u\/34s\/bca3b80481394e25b03f4fc77c338897.png",
"size": "small"
},
{
"#text": "https:\/\/lastfm-img2.akamaized.net\/i\/u\/64s\/bca3b80481394e25b03f4fc77c338897.png",
"size": "medium"
}
],
"streamable": "0",
"mbid": "c559efc2-f734-41ae-93bd-2d78414e0356"
},
{
"name": "Believe",
"artist": "Justin Bieber",
"url": "https:\/\/www.last.fm\/music\/Justin+Bieber\/Believe",
"image": [
{
"#text": "https:\/\/lastfm-img2.akamaized.net\/i\/u\/34s\/899fe1643173a9568ac6e832327e7b57.png",
"size": "small"
},
{
"#text": "https:\/\/lastfm-img2.akamaized.net\/i\/u\/64s\/899fe1643173a9568ac6e832327e7b57.png",
"size": "medium"
}
],
"streamable": "0",
"mbid": "5d88ae0c-c4bf-4e64-bc97-45789880d910"
}
}
代码:
struct SearchResults: Decodable {
let results: Results
}
struct Results: Decodable {
let albumMatches: AlbumMatches
enum CodingKeys: String, CodingKey {
case albumMatches = "albummatches"
}
}
struct AlbumMatches: Decodable {
let album: [Album]
}
struct Album: Decodable {
let name: String?
let image: [String]
let artist: String?
}
class APIService {
static let shared = APIService()
func fetchArtists(searchText: String, url: URL, completionHandler: @escaping ([Album]) ->()) {
Alamofire.request(url, method: .get, encoding: URLEncoding.default, headers: nil).responseData { (dataResponse) in
if let error = dataResponse.error {
print("Failed to contact last fm", error)
return
}
guard let data = dataResponse.data else { return }
do {
let decoder = JSONDecoder()
let searchResult = try decoder.decode(SearchResults.self, from: data)
searchResult.results.albumMatches.album.forEach({ (album) in
print(searchResult.results.albumMatches.album)
})
} catch let decodeError {
print("Failed to decode", decodeError)
}
}
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print(searchText)
let baseLastfmUrl = "http://ws.audioscrobbler.com/2.0/?method=album.search&album=believe&api_key=MyKey&format=json"
guard let url = URL(string: baseLastfmUrl) else { return }
APIService.shared.fetchArtists(searchText: searchText, url: url) { (album) in
self.albums = album
self.tableView.reloadData()
}
}
【问题讨论】:
标签: json swift alamofire decodable