无法用Swift解码器进行解码[英] Unable to decode with Swift decodable

本文是小编为大家收集整理的关于无法用Swift解码器进行解码的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我无法弄清楚为什么这不起作用.在互联网上,我发现了许多与本地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"
            }
        }....

推荐答案

而不是类别结构...您应该拥有这些结构

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

本文地址:https://www.itbaoku.cn/post/1937802.html

问题描述

I can not figure out why this doesn't work. On the internet I found a lot of solutions with local json(not api) or with api without apiKey which in my case must be in the header(tested in 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()
        }
    }

I removed the urlString and api_key from the code above, but I am sure they are ok because I tested them in Postman
Problem - always getting printed Fetch failed: Unknown error
Here is how my json looks like:

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

推荐答案

Instead of just categories struct ... you should have these structs

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