Last.fm api json 没有被 swift 解码器读取

Last.fm api json not being read with swift decoder

我正在尝试使用 last.fm api 和 swift ui 制作一个简单的歌曲搜索应用程序。当我将解码器与 iTunes api 一起使用时,它工作正常,但是当我尝试使用 last.fm 时,我的视图是空白的,所以我假设可能是我为 json 定义的对象错了? swift 有点新手,尤其是阅读 api 中的 json 文件时非常困惑。任何 help/tips 将不胜感激。

api link: https://www.last.fm/api/show/track.search

json link: http://ws.audioscrobbler.com/2.0/?method=track.search&track=hello&api_key=d527fc1829aecc7e54b63367b3d4621a&format=json


struct TracksRow: View {
    @State var term = "hello"
    @State var results = [Tracks]()
    
    var body: some View {
        List(results, id: \.songName){ item in
            VStack(alignment: .leading) {
                Text(item.songName)
                    .font(.headline)
                Text(item.singerName)
            }
        }.onAppear(perform: loadData)
        
    }
    
    func loadData(){
        guard let url = URL(string: "http://ws.audioscrobbler.com/2.0/?method=track.search&track=\(term)&api_key=d527fc1829aecc7e54b63367b3d4621a&format=json") else {
            print("Invalid URL")
            return
        }
        
        let request = URLRequest(url: url)
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(SongResponse.self, from: data) {
                    
                    DispatchQueue.main.async {
                        self.results = decodedResponse.songs.trackMatches.matches
                    }
                    
                    return
                }
            }
            
        }.resume()
        
        
    }
}

struct TracksRow_Previews: PreviewProvider {
    static var previews: some View {
        TracksRow()
    }
}

JSON 对象:


struct SongResponse: Codable{
    let songs : TrackResults
    
    enum CodingKeys: String, CodingKey {
        case songs = "results"
    }
}

struct TrackResults: Codable {
    var trackMatches: TrackMatches
   
    enum CodingKeys: String, CodingKey {
        case trackMatches = "trackmatches"
    }
}

struct TrackMatches: Codable {
    let matches : [Tracks]
    
    enum CodingKeys: String, CodingKey {
        case matches = "track"
    }
}

struct Tracks: Codable {
     let songName: String
     let singerName: String
     let albumImage: [TrackImage]
    
    enum CodingKeys: String, CodingKey {
        case songName = "name"
        case singerName = "artist"
        case albumImage = "image"
    }
}

struct TrackImage: Codable{
    let url: String
    let size: String
    
    enum CodingKeys: String, CodingKey{
        case url = "#text"
        case size
    }
}

我在使用您的代码解析 API 时没有遇到任何问题。我认为 JSON 解析没有任何问题, 您是否更新了 info.plist App Transport 安全性?

这是假设您添加了上述密钥后您的代码显示的内容。