json - 如何使用 swift 4 和 struct 从字典中获取数据?
问题描述
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))
解决方案
问题是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()
}
}
推荐阅读
- cygwin - 兼容性层与虚拟化层
- r - 数据表 lapply 和输出中的附加列
- python - 来自谷歌的 400 错误请求
- java - Vert.x:一个 ChainAuthHandler 中的多个 JWTAuthHandler
- jhipster - jHipster 显示“发生错误 :-(” 在 Internet Explorer 中打开应用程序时,但在 chrome 浏览器中工作正常
- java - 如何指定该用户是否已共享我的应用 x 次?
- lua - Kong v1.0.2 的自定义插件已启用但未安装
- python - 如何摆脱python中的嵌套循环
- c# - 使用双泛型的 C# 类:当它们都应该相同时只给出一个?
- python - Python:针对不同特定工作人员的分布式任务队列