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

时间:2018-11-12 22:04:59

标签: ios json swift alamofire codable

这是我的第一篇文章。到目前为止,我自己总是能找到答案,但是今天,经过大量的研究,我仍然犹豫不决……

这是我的问题,我从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)
        }
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

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)
}