如何使用swift 4和struct从字典中获取数据?

时间:2019-03-28 13:29:43

标签: json swift codable

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:“没有与键CodingKeys(stringValue:\” userId \“,intValue:nil相关联的值) )(\“ userId \”)。“,underlyingError:nil))

1 个答案:

答案 0 :(得分:0)

问题是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()
    }
}