【问题标题】:how to fetch data from a dictionary using swift 4 and struct?如何使用 swift 4 和 struct 从字典中获取数据?
【发布时间】:2019-08-19 07:10:35
【问题描述】:
struct family: Decodable {
    let userId: [String:Int]
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = "http://supinfo.steve-colinet.fr/supfamily?action=login&username=admin&password=admin"
        let urlobj = URL(string: url)
        URLSession.shared.dataTask(with: urlobj!){(data, response, error) in
            do{
                let member = try JSONDecoder().decode(family.self, from: data!)
                print(member)
            }catch{
                print(error)
            }
        }.resume()
    }
}

错误:

keyNotFound(CodingKeys(stringValue: "userId", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"userId\", intValue: nil ) (\"userId\").", 底层错误: nil))

【问题讨论】:

    标签: json swift codable


    【解决方案1】:

    问题在于 userId 键嵌套在 JSON 响应中。您需要从其根目录解码响应。

    struct Family: Decodable {
        let id: Int
        let name: String
    }
    
    struct User: Codable {
        let userId: Int
        let lasName: String
        let firstName: String
    }
    
    struct RootResponse: Codable {
        let family: Family
        let user: User
    }
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            let url = "http://supinfo.steve-colinet.fr/supfamily?action=login&username=admin&password=admin"
            let urlobj = URL(string: url)
            URLSession.shared.dataTask(with: urlobj!){(data, response, error) in
                do{
                    let rootResponse = try JSONDecoder().decode(RootResponse.self, from: data!)
                    print(rootResponse)
                }catch{
                    print(error)
                }
            }.resume()
        }
    }
    

    【讨论】:

    • 非常感谢,这是我第一次测试stackoverflow的威力!
    猜你喜欢
    • 1970-01-01
    • 2018-09-09
    • 2018-11-23
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多