无法使用Swift解码器进行解码

问题描述

我不知道为什么这行不通。在互联网上,我发现了很多使用本地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()
        }
    }

我从上面的代码删除urlStringapi_key,但是我确信它们还可以,因为我在Postman中对其进行了测试
问题-总是打印Fetch Failed: UnkNown error
这是我的json的样子:

{
    "categories": [
        {
            "categories": {
                "id": 1,"name": "A"
            }
        },{
            "categories": {
                "id": 2,"name": "B"
            }
        }....

解决方法

您不仅应该拥有这些结构,还应该拥有这些结构

// 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)
        }
    }
}