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

标签 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: "No value associated with key CodingKeys(stringValue: \"userId\", intValue: nil) (\"userId\").", underlyingError: nil))

最佳答案

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

关于json - 如何使用 swift 4 和 struct 从字典中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55398868/

相关文章:

php - Redis中存储树结构

java - 从mongodb中获取数据并插入到mongodb中

swift 3 : Share Button of Facebook SDK is Disabled

json - SwiftUI - 类型 'Service' 不符合协议(protocol) 'Decodable'

json - 将未知的 Encodable 枚举值解码为默认值

javascript - 如何在 AngularJS 中与服务进行双向数据绑定(bind)?

javascript - 对表值进行分组并将其他值相加

ios - NSCache 和持久性?

objective-c - 桥接 Swift 和 Objective-C 不能完全工作

swift - Codable 和自定义 Getter 构建错误