无法使用Swift可解码

问题描述 投票:0回答:1

我不明白为什么这不起作用。在互联网上,我发现了很多使用本地 JSON(不是 API)或使用不带

apiKey
的 API 的解决方案,在我的情况下,它必须位于标头中(在 Postman 中测试)。

struct Categories: Decodable {
        let name: String
        let id: Int
    }
    
    class ViewController: UIViewController {
        
        
        let api_key = "..."
        
        let urlString = "..."

        override func viewDidLoad() {
            super.viewDidLoad()
            
            let url = URL(string: urlString)
            
            var request = URLRequest(url: url!)
            
            request.addValue(api_key, forHTTPHeaderField: "user-key")
            request.httpMethod = "GET"
            
            URLSession.shared.dataTask(with: request) { data, response, error in
                if let data = data {
                    if let category = try? JSONDecoder().decode(Categories.self, from: data) {
                            print(category.name)
                        return
                    }
                }
                
                print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
            }.resume()
        }
    }

我从上面的代码中删除了

urlString
api_key
,但我确信它们没问题,因为我在
Postman
中测试了它们
问题 - 总是被打印:

Fetch failed: Unknown error

我的 JSON 如下所示:

{
    "categories": [
        {
            "categories": {
                "id": 1,
                "name": "A"
            }
        },
        {
            "categories": {
                "id": 2,
                "name": "B"
            }
        }....
ios json swift decodable
1个回答
3
投票

你应该拥有这些结构,而不仅仅是类别结构

// MARK: - Category
struct Category: Codable {
    let categories: [CategoryElement]
}

// MARK: - CategoryElement
struct CategoryElement: Codable {
    let categories: Categories
}

// MARK: - Categories
struct Categories: Codable {
    let id: Int
    let name: String
}




URLSession.shared.dataTask(with: request) { data, response, error in
    if let data = data {
        do {
            // process data
            if let category = try JSONDecoder().decode(Category.self, from: data) { print(category) }
        } catch  {
            print(error)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.