Как получить данные из словаря с помощью Swift 4 и структуры? - PullRequest
0 голосов
/ 28 марта 2019
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 \"). ", underError: nil))

1 Ответ

0 голосов
/ 28 марта 2019

Проблема в том, что ключ 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()
    }
}
...