gpt4 book ai didi

ios - 如何在 Swift 4 中解析来自 Alamofire 的数据

转载 作者:可可西里 更新时间:2023-11-01 00:54:24 24 4
gpt4 key购买 nike

这是我的第一篇文章。到目前为止,我总是自己找到答案,但今天,经过大量研究,我仍然碰壁......

这是我的问题,我从 Alamofire 请求中获取了一个 JSON,但我无法按照我的意愿解析我的数据。

我有这个答案:

{"family": {"id":1, "name": "myFamily","members": [{"userId":15, "lasName": "COLINET", "firstName":"Steve","latitude":48.290762, "longitude":4.070 },{"userId":18,"lasName":"BERTHIER","firstName":"Renaud","latitude":48.290755, "longitude":4.071 }]}}

我想获得一个成员列表,我可以从中获取名字/姓氏和纬度/经度。我已经尝试了很多我无法列举的东西......

这是我现在拥有的(错误的)代码:

func getMembers(username:String, password:String){
var members:NSDictionary = [:]
let parameters: Parameters=[
"action":"getPosition",
"username":"\(username)",
"password":"\(password)"
]
Alamofire.request(login_url, method: .post, parameters: parameters).responseJSON{
response in

switch response.result {
case .success(let data):
guard let json = data as? [String : AnyObject] else { return }
members = json["family"]!["members"] as! NSDictionary
members.forEach { member in
print(member["firstName"])
}
case .failure(let error):
print(error)
}
}
}

感谢您的帮助。

最佳答案

members 是数组而不是字典

 if let family = json["family"] as? [String:Any] {
if let members = family["members"] as? [[String:Any]] {
print(members)
}
}

最好用

struct Root: Codable {
let family: Family
}

struct Family: Codable {
let id: Int
let name: String
let members: [Member]
}

struct Member: Codable {
let userID: Int
let lasName, firstName: String
let latitude, longitude: Double

enum CodingKeys: String, CodingKey {
case userID = "userId"
case lasName, firstName, latitude, longitude
}
}

do {
let tr = try JSONDecoder().decode(Root.self,from:jsonData)
print(tr.family.members)
}
catch {

print(error)
}

关于ios - 如何在 Swift 4 中解析来自 Alamofire 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53270775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com